csv #
一个快速且灵活的Rust CSV读写器,支持Serde序列化。
1cargo add csv
快速示例 #
这个示例展示了如何从标准输入读取CSV数据并将每条记录打印到标准输出。
1use std::{error::Error, io, process};
2
3fn example() -> Result<(), Box<dyn Error>> {
4 // Build the CSV reader and iterate over each record.
5 let mut rdr = csv::Reader::from_reader(io::stdin());
6 let headers: &csv::StringRecord = rdr.headers()?;
7 println!("{:?}", headers);
8 for result in rdr.records() {
9 // The iterator yields Result<StringRecord, Error>, so we check the
10 // error here.
11 let record: csv::StringRecord = result?;
12 println!("{:?}", record);
13 }
14 Ok(())
15}
16
17fn main() {
18 if let Err(err) = example() {
19 println!("error running example: {}", err);
20 process::exit(1);
21 }
22}
1cargo run < ./data/example.csv
使用Serde的示例 #
本示例展示如何将CSV数据从标准输入读取到自定义的结构体中。默认情况下,结构体的成员名称会与CSV数据的标题记录中的值相匹配。
1use std::{error::Error, io, process};
2
3#[derive(Debug, serde::Deserialize)]
4#[serde(rename_all = "camelCase")] // https://serde.rs/container-attrs.html
5struct Record {
6 city: String,
7 region: String,
8 country: String,
9 #[serde(rename = "population")]
10 population: Option<u64>,
11}
12
13fn example() -> Result<(), Box<dyn Error>> {
14 let mut rdr = csv::Reader::from_reader(io::stdin());
15 for result in rdr.deserialize() {
16 // Notice that we need to provide a type hint for automatic
17 // deserialization.
18 let record: Record = result?;
19 println!("{:?}", record);
20 }
21 Ok(())
22}
23
24fn main() {
25 if let Err(err) = example() {
26 println!("error running example: {}", err);
27 process::exit(1);
28 }
29}
1cargo run < ./data/smallpop.csv