From bc40f1153cb731a55338ab318f62e77aa3a3edac Mon Sep 17 00:00:00 2001
From: Anders Nilsson <anders.nilsson@control.lth.se>
Date: Mon, 30 Nov 2015 14:55:58 +0100
Subject: [PATCH] Some error handling included

---
 city-pop/src/main.rs | 36 ++++++++++++++++++++++++------------
 1 file changed, 24 insertions(+), 12 deletions(-)

diff --git a/city-pop/src/main.rs b/city-pop/src/main.rs
index 6c6dd25..7737fce 100644
--- a/city-pop/src/main.rs
+++ b/city-pop/src/main.rs
@@ -26,7 +26,7 @@ struct Row {
 
 struct PopulationCount {
     city: String,
-    country: String
+    country: String,
     // This is no longer an `Option` because values of this type are only
     // constructed if they have a population count.
     count: u64,
@@ -36,6 +36,26 @@ fn print_usage(program: &str, opts: Options) {
     println!("{}", opts.usage(&format!("Usage: {} [options] <data-path> <city>",program)));
 }
 
+fn search<P: AsRef<path::Path>>(file_path: P, city: &str) -> Vec<PopulationCount> {
+    let mut found = vec![];
+    let file = fs::File::open(file_path).unwrap();
+    let mut rdr = csv::Reader::from_reader(file);
+    for row in rdr.decode::<Row>() {
+        let row = row.unwrap();
+        match row.population {
+            None => { }
+            Some(count) => if row.city == city {
+                found.push(PopulationCount {
+                    city: row.city,
+                    country: row.country,
+                    count: count,
+                });
+            },
+        }
+    }
+    found
+}
+
 fn main() {
     let args: Vec<String> = env::args().collect();
     let program = args[0].clone();
@@ -56,16 +76,8 @@ fn main() {
     let data_path = path::Path::new(&data_file);
     let city = args[2].clone();
 
-    let file = fs::File::open(data_path).unwrap();
-    let mut rdr = csv::Reader::from_reader(file);
-
-    for row in rdr.decode::<Row>() {
-        let row = row.unwrap();
-
-        if row.city == city {
-            println!("{}, {}: {:?}",
-                     row.city, row.country,
-                     row.population.expect("population count"));
-        }
+    for pop in search(&data_path, &city) {
+        println!("{}, {}: {:?}",pop.city, pop.country, pop.count);
     }
+
 }
-- 
GitLab