blob: 54e85a5cd4a0e30115e48b88f7316464d054db2a [file] [log] [blame]
Jakub Koturc72d7202020-12-21 17:28:15 +01001use std::error::Error;
2use std::io;
3use std::process;
4
5use serde::Serialize;
6
7#[derive(Debug, Serialize)]
8struct Record {
9 city: String,
10 region: String,
11 country: String,
12 population: Option<u64>,
13}
14
15fn 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
36fn main() {
37 if let Err(err) = example() {
38 println!("error running example: {}", err);
39 process::exit(1);
40 }
41}