How to read-in a file line-by-line as integer?
Hello there!
I'm quite new to rust and just started a few days ago to read the book.
To get a littlebit more used to programming with rust I decided to participate on "advent of code", but I already struggling with 'easy' tasks like fs-operations..
fn read_line() -> Result<(), Error> {
let file = "./list.txt";
let input = File::open(file)?;
let buffered = BufReader::new(input);
let mut vec = Vec::<u32>::new();
for line in buffered.lines() {
vec.push(line?.trim().parse())
}
Ok(())
}
Apparently I messed things up in my function and I'm pretty much confused.. The Compiler gives my the following error:
error[E0308]: mismatched types
--> src/main.rs:14:18
|
14 | vec.push(line?.trim().parse())
| ^^^^^^^^^^^^^^^^^^^^ expected `u32`, found enum `Result`
|
= note: expected type `u32`
found enum `Result<_, _>`
I thought, I can parse the line to an unsigned integer because it represents the just read-in line as a string. But the error says that I can't push a value to my vector, because it's from type 'Result' and not type 'u32'. So far, I would agree with the compiler. I can't push a wrong type to my u32-vector. But why is my line a Result and not a String?
My goal is to read-in a file line-by-line, parse the string to integer and push it to my vector.
Can somebody please explain it to me ? If possible, beginner-friendly?
Thank you!