read a csv file in rust

To read a CSV file in Rust, we first need to add the csv and serde crates to our Cargo.toml file:

[dependencies]
csv = "1.1.6"
serde = { version = "1.0", features = ["derive"] }
80 chars
4 lines

Here's an example of how to use these crates to read data from a CSV file:

main.rs
use serde::Deserialize;
use std::error::Error;
use std::fs::File;

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

fn main() -> Result<(), Box<dyn Error>> {
    let file = File::open("data.csv")?;
    let mut reader = csv::Reader::from_reader(file);

    for result in reader.deserialize::<Record>() {
        let record: Record = result?;
        println!("{:?}", record);
    }

    Ok(())
}
445 chars
23 lines

In this example, we define a Record struct that represents the data in our CSV file. We use the serde crate to deserialize the CSV data into this struct.

We first open the file using File::open() and check if it returns an error. We then create a csv::Reader object from the file, which will allow us to read the CSV data.

We then use a for loop to iterate over each record in the CSV file. For each record, we deserialize it into a Record struct using deserialize() and print it out.

Finally, we return Ok(()) to indicate that our program executed successfully. If any errors occurred, we return a Box<dyn Error> containing the error message.

gistlibby LogSnag