Skip to content
Snippets Groups Projects
Commit bc40f115 authored by Anders Nilsson's avatar Anders Nilsson
Browse files

Some error handling included

parent 722c9b4c
Branches
No related tags found
No related merge requests found
......@@ -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);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment