diff --git a/city-pop/src/main.rs b/city-pop/src/main.rs index 6c6dd25a05dbbd729da0dcdea2fcb9323f2612ba..7737fce21678db1b68afe3d17a5a51bc24f36260 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); } + }