In this function parse
can return an error so I use .filter_map(Result::ok)
to filter them out.
fn part1(input: &str) {
let sum = input.lines()
.map(|l| l.parse::<u32>())
.filter_map(Result::ok)
.map(|n| n as f32 / 3.0)
.map(|f| f.round())
.map(|f| f as u32 - 2)
.sum::<u32>();
// println!("{}", sum);
println!("{:?}", sum);
}
However, I would like to return out of the part1
function when parse gives an error, kind of like using the question mark operator like this .map(|l| l.parse::<u32>()?)
. If this is done the compiler gives the error
error[E0277]: the `?` operator can only be used in a closure that returns `Result`
or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:64:18
|
64 | .map(|l| l.parse::<u32>()?)
| ----^^^^^^^^^^^^^^^^^
| | |
| | cannot use the `?` operator in a closure that returns `u32`
| this function should return `Result` or `Option` to accept `?`
Is this because the question mark operator is used inside a closure so it returns out of the closure instead of the enclosing function? What are some idiomatic alternatives to using the question mark operator inside the closure so that I can return out of part1
if parse
gives an error or unwrap the Ok
if parse is successful? The result should be similar to .filter_map(Result::ok)
, except instead of filtering out the errors it will return out of the enclosing function when there is an error.