Jakub Kotur | c72d720 | 2020-12-21 17:28:15 +0100 | [diff] [blame] | 1 | use std::error::Error; |
| 2 | use std::io; |
| 3 | use std::process; |
| 4 | |
| 5 | // This lets us write `#[derive(Deserialize)]`. |
| 6 | use serde::Deserialize; |
| 7 | |
| 8 | // We don't need to derive `Debug` (which doesn't require Serde), but it's a |
| 9 | // good habit to do it for all your types. |
| 10 | // |
| 11 | // Notice that the field names in this struct are NOT in the same order as |
| 12 | // the fields in the CSV data! |
| 13 | #[derive(Debug, Deserialize)] |
| 14 | #[serde(rename_all = "PascalCase")] |
| 15 | struct Record { |
| 16 | latitude: f64, |
| 17 | longitude: f64, |
| 18 | population: Option<u64>, |
| 19 | city: String, |
| 20 | state: String, |
| 21 | } |
| 22 | |
| 23 | fn run() -> Result<(), Box<dyn Error>> { |
| 24 | let mut rdr = csv::Reader::from_reader(io::stdin()); |
| 25 | for result in rdr.deserialize() { |
| 26 | let record: Record = result?; |
| 27 | println!("{:?}", record); |
| 28 | // Try this if you don't like each record smushed on one line: |
| 29 | // println!("{:#?}", record); |
| 30 | } |
| 31 | Ok(()) |
| 32 | } |
| 33 | |
| 34 | fn main() { |
| 35 | if let Err(err) = run() { |
| 36 | println!("{}", err); |
| 37 | process::exit(1); |
| 38 | } |
| 39 | } |