How to get first column from library rust-csv?


#1

My source code:
extern crate csv;

fn main() {
    let mut rdr = csv::Reader::from_file("./data/simple.csv").unwrap();
    for record in rdr.decode() {
        let row: String = record.unwrap()[0];
        println!("{}", row);
    }
}

My error:

cargo run
   Compiling moex_analytic_rust v0.0.1 (file:///home/dmitry/web/moex_analytic_rust)
src/main.rs:11:31: 11:49 error: the type of this value must be known in this context
src/main.rs:11             let row: String = record.unwrap()[0];
                                             ^~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `moex_analytic_rust`.

To learn more, run the command again with --verbose.

#2

See http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.decode
decode returns something that must know D type.
To fix you should write

fn main() {
    let mut rdr = csv::Reader::from_file("./data/simple.csv").unwrap();
    for record in rdr.decode::<String>() {
        let row: String = record.unwrap()[0];
        println!("{}", row);
    }
}

#3

If you just want to get a row of strings, then use the records iterator, as demonstrated in the example here: http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.records

If you want to use the automatic deserialization machinery (e.g., your row contains strings, integers, enums, or whatever), then you should use decode. If you use decode, you will need to specify the type of the row (so simply String will not work). There are several examples/explanations here: http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.decode


#4

Thanks!
If I hear you aright object record need convert into String type?


#5

the problem is that I don’t know how many columns. This examples for files with fixed numbers of columns.


#6
extern crate csv;

use std::fs;
use std::string::String;

fn main() {
    let mut rdr = csv::Reader::from_file("./data/simple.csv").unwrap();
    for record in rdr.records() { 
        let row: Vec<String> = record.unwrap();
        println!("{}", row[0]);
    }
}

This is work solution this task.