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 | fn run() -> Result<(), Box<dyn Error>> { |
| 6 | let mut wtr = csv::Writer::from_writer(io::stdout()); |
| 7 | |
| 8 | // We still need to write headers manually. |
| 9 | wtr.write_record(&[ |
| 10 | "City", |
| 11 | "State", |
| 12 | "Population", |
| 13 | "Latitude", |
| 14 | "Longitude", |
| 15 | ])?; |
| 16 | |
| 17 | // But now we can write records by providing a normal Rust value. |
| 18 | // |
| 19 | // Note that the odd `None::<u64>` syntax is required because `None` on |
| 20 | // its own doesn't have a concrete type, but Serde needs a concrete type |
| 21 | // in order to serialize it. That is, `None` has type `Option<T>` but |
| 22 | // `None::<u64>` has type `Option<u64>`. |
| 23 | wtr.serialize(( |
| 24 | "Davidsons Landing", |
| 25 | "AK", |
| 26 | None::<u64>, |
| 27 | 65.2419444, |
| 28 | -165.2716667, |
| 29 | ))?; |
| 30 | wtr.serialize(("Kenai", "AK", Some(7610), 60.5544444, -151.2583333))?; |
| 31 | wtr.serialize(("Oakman", "AL", None::<u64>, 33.7133333, -87.3886111))?; |
| 32 | |
| 33 | wtr.flush()?; |
| 34 | Ok(()) |
| 35 | } |
| 36 | |
| 37 | fn main() { |
| 38 | if let Err(err) = run() { |
| 39 | println!("{}", err); |
| 40 | process::exit(1); |
| 41 | } |
| 42 | } |