How to Use Serde with CSV Files in Rust

Use the csv crate with Serde's Deserialize derive macro to parse CSV files into Rust structs efficiently.

Use the csv crate with Serde to parse CSV files into structs by deriving Deserialize and calling Reader::from_path.

[dependencies]
serde = { version = "1.0", features = ["derive"] }
csv = "1.3"
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Record {
    name: String,
    age: u32,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut rdr = csv::Reader::from_path("data.csv")?;
    for result in rdr.deserialize() {
        let record: Record = result?;
        println!("{:?}", record);
    }
    Ok(())
}