Transform StringRecord to String

Hi, I'm new in Rust and I am trying to read a .csv and work with the content of it. What I want to do is to read each word separated by ";" and be able to save it in a string in order to work with that.

Thank you for your help!
Code:

    let mut reader = ReaderBuilder::new().delimiter(b';').from_path(path)?;
    for result in reader.records() {
        let record = result?; 
        let mut sentencia = String::from(record); <-- This is where I want to conver to String.
        println!("{:?}gjk", record);
    }
    Ok(())
}

Welcome! In the future, please place your code samples inside Markdown code blocks (a line of three backticks in a row ```, followed by your pasted code, followed by another line of three backticks) and use plain text, not screenshots, for all code and compiler diagnostics, to make your posts easier for us to read.

To answer your question, you can get the underlying CSV row as a &str (shared reference to string slice) from a StringRecord using the StringRecord::as_slice method. If you need an owned String you can then call .to_owned() on this &str value.

If you want to get a &str for each field within each row/record, you can loop over them like this (I've corrected a typo, Result<(), Box> should most likely be Result<(), Box<dyn std::error::Error>>):

fn leer_archivo(path: &str) -> Result<(), Box<dyn std::error::Error>> {
    let mut reader = ReaderBuilder::new().delimiter(b';').from_path(path)?;
    for result in reader.records() {
        let record = result?;
        for field in &record {
            println!("{:?}", field);
        }
    }
    Ok(())
}
2 Likes

Thank you for your help! Actually after I posted this, I tried doing println!("{:?}", record); and it kinda worked but your code helps me with other things I wanted to do. So thank you very much! :slight_smile:

2 Likes

println!("{:?}", record) works because StringRecord implements the Debug trait, which is invoked when you print a value using the {:?} syntax.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.