Reputation: 60759
I am very new to rust, and I'm trying to make a programme that reads stdin, splits each line based on the ,
character and prints the first item (a simple CSV-like / unix programme).
This is the programme and the compiler error is below.
use std::io;
fn main() {
let mut stdin = io::stdin();
for line in stdin.lines() {
let fields = line.unwrap().as_slice().split_str(",").collect();
print!("{}", fields[0]);
}
}
And I get this error:
groupby.rs:12:22: 12:31 error: the type of this value must be known in this context
groupby.rs:12 print!("{}", fields[0]);
^~~~~~~~~
I have no idea what's going on, nor why this doesn't work. Shouldn't it be obvious (to the compiler) that fields
is now a Vec of strings(-type things)?
This is rustc 0.12.0-pre from the Ubuntu nightly PPA (201409260407~bb66281 )
Upvotes: 1
Views: 199
Reputation: 65822
The problem comes from collect()
. Iterator::collect()
's return type is generic: it can be any type that implements FromIterator<T>
. Vec<T>
is such a type. You simply need to add a type annotation:
use std::io;
fn main() {
let mut stdin = io::stdin();
for line in stdin.lines() {
let line = line.unwrap(); // must bind the result of unwrap()
// to fix a lifetime error
let fields: Vec<&str> = line.as_slice().split_str(",").collect();
print!("{}", fields[0]);
}
}
Upvotes: 3