I'm having trouble figuring out how to pass an error through a closure idiomatically.
I'm trying to have this piece of code print Ok([0, 1, 0, 2, 0, 3])
.
fn increment(n: u8) -> Result<Vec<u8>, String> {
Ok(vec![0,n])
}
fn build_big_vec() -> Result<Vec<u8>, String> {
let nums = vec![1u8, 2, 3];
let bigvec: Vec<u8> = nums
.iter()
.map(|&n| increment(n)?)
.flatten()
.collect();
Ok(bigvec)
}
fn main() {
let bigvec = build_big_vec();
println!("bigvec: {:?}", bigvec);
}
If I change .map(|&n| increment(n)?)
to .map(|&n| increment(n).unwrap())
, it works perfectly. I guess I could use a for
loop instead of a map
, but was wondering if there was a better alternative.