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 | use serde::Deserialize; |
| 6 | |
| 7 | // By default, struct field names are deserialized based on the position of |
| 8 | // a corresponding field in the CSV data's header record. |
| 9 | #[derive(Debug, Deserialize)] |
| 10 | struct Record { |
| 11 | city: String, |
| 12 | region: String, |
| 13 | country: String, |
| 14 | population: Option<u64>, |
| 15 | } |
| 16 | |
| 17 | fn example() -> Result<(), Box<dyn Error>> { |
| 18 | let mut rdr = csv::Reader::from_reader(io::stdin()); |
| 19 | for result in rdr.deserialize() { |
| 20 | // Notice that we need to provide a type hint for automatic |
| 21 | // deserialization. |
| 22 | let record: Record = result?; |
| 23 | println!("{:?}", record); |
| 24 | } |
| 25 | Ok(()) |
| 26 | } |
| 27 | |
| 28 | fn main() { |
| 29 | if let Err(err) = example() { |
| 30 | println!("error running example: {}", err); |
| 31 | process::exit(1); |
| 32 | } |
| 33 | } |