I'm trying to read in a list of numbers from a file (where each line has a number on it) into a Vec<i64>
with Rust. I can get the numbers loaded from the file as strings using a BufReader
. However, I can't seem to get the value of the strings out of the Result
enum they are wrapped in by the BufReader
.
So how does one get those values out of Result
to parse, so they can populate a Vec
with another type than strings?
What I have tried:
- Using a
for
loop where I can print the values to prove they're there, but it panics on the parse when I try to compile with thenumbers.append(...)
line.
fn load_from_file(file_path: &str) {
let file = File::open(file_path).expect("file wasn't found.");
let reader = BufReader::new(file);
let numbers: Vec<i64> = Vec::new();
for line in reader.lines() {
// prints just fine
println!("line: {:?}", line);
numbers.append(line.unwrap().parse::<i64>());
}
}
- Alternatively I tried mapping instead, but I encounter the same issue with getting the values into the
Vec<i64>
I'm trying to populate.
fn load_from_file(file_path: &str) {
let file = File::open(file_path).expect("file wasn't found.");
let reader = BufReader::new(file);
let numbers: Vec<i64> = reader
.lines()
.map(|line| line.unwrap().parse::<i64>().collect());
}
This is not solved solely by How to do error handling in Rust and what are the common pitfalls?