Nicke7117
Nicke7117

Reputation: 197

Error: no method named `parse` found for enum `Result` in the current scope

I'm trying to read a txt file with numbers like 1234 823, I want to convert those into an u16 and .collect() them into a vec. It gives me this error: no method named "parse" found for enum "Result" in the current scope. So how can i fix this?

let file_in = fs::File::open("input.txt").unwrap(); 
let file_reader = BufReader::new(file_in); 
let vec: Vec<u16> = file_reader.lines().map(|x| x.parse::<u16>().unwrap()).collect();

Upvotes: 1

Views: 5184

Answers (1)

user459872
user459872

Reputation: 24602

The lines returns an iterator which yield instances of io::Result<String>. So you can unwrap instance to get the contained Ok value.

let vec: Vec<u16> = file_reader
    .lines()
    .map(|x| x.unwrap().parse::<u16>().unwrap())
    .collect();

But this will panic if any of the line is failed to parse(to u16). So you can use filter_map instead.

let vec: Vec<u16> = file_reader
    .lines()
    .filter_map(|x| x.unwrap().parse::<u16>().ok())
    .collect();

Upvotes: 1

Related Questions