write to a csv file in rust

To write to a CSV (Comma Separated Values) file in Rust, we can use the csv crate. Here's an example code snippet that demonstrates how to write to a CSV file:

main.rs
extern crate csv;

use std::error::Error;
use std::fs::File;

#[derive(Debug, serde::Serialize)]
struct Person {
    name: String,
    age: u32,
    phone: String,
}

fn write_to_csv() -> Result<(), Box<dyn Error>> {
    let people = vec![
        Person {
            name: String::from("Alice"),
            age: 25,
            phone: String::from("123-456-7890"),
        },
        Person {
            name: String::from("Bob"),
            age: 30,
            phone: String::from("234-567-8901"),
        },
        Person {
            name: String::from("Charlie"),
            age: 35,
            phone: String::from("345-678-9012"),
        },
    ];

    let file = File::create("people.csv")?;
    let mut writer = csv::Writer::from_writer(file);

    for person in people {
        writer.serialize(person)?;
    }

    Ok(())
}
845 chars
41 lines

In this example, the Person struct represents the data we want to write to the CSV file. We then create a vector of Person objects and open a new file called people.csv for writing. We then create a csv::Writer object from the file and iterate over each Person object in the vector, serializing and writing it to the CSV file using the writer.serialize(person)? method call.

Note that we are also using the serde crate for serializing the Person struct to CSV format.

Lastly, to handle any errors that may occur while writing to the CSV file, we return a Result object containing either Ok(()) on success or a boxed dyn Error object on failure.

gistlibby LogSnag