1 use std::error::Error;
2 use std::io;
3 use std::process;
4 
5 use serde::Serialize;
6 
7 #[derive(Debug, Serialize)]
8 struct Record {
9     city: String,
10     region: String,
11     country: String,
12     population: Option<u64>,
13 }
14 
example() -> Result<(), Box<dyn Error>>15 fn example() -> Result<(), Box<dyn Error>> {
16     let mut wtr = csv::Writer::from_writer(io::stdout());
17 
18     // When writing records with Serde using structs, the header row is written
19     // automatically.
20     wtr.serialize(Record {
21         city: "Southborough".to_string(),
22         region: "MA".to_string(),
23         country: "United States".to_string(),
24         population: Some(9686),
25     })?;
26     wtr.serialize(Record {
27         city: "Northbridge".to_string(),
28         region: "MA".to_string(),
29         country: "United States".to_string(),
30         population: Some(14061),
31     })?;
32     wtr.flush()?;
33     Ok(())
34 }
35 
main()36 fn main() {
37     if let Err(err) = example() {
38         println!("error running example: {}", err);
39         process::exit(1);
40     }
41 }
42