I am mapping over Vec
such that each item becomes a Result
. If any element is an Err
then I want to terminate early and produce an Err
, otherwise I want to produce an Ok
containing the Vec<i32>
.
let v = (1..10)
.map( |n| {
if n % 4 == 0 {
Err("Too fourish!")
}
else {
Ok(n)
}
}).collect::<Vec<_>>();
println!("{:?}", v);
In Haskell, I can use sequence
. Is there an equivalent built-in Rust function?
You can use the FromIterator
implementation of Result
for this:
fn main() {
let v = (1..10)
.map( |n| {
if n % 4 == 0 {
Err("Too fourish!")
}
else {
Ok(n)
}
}).collect::<Result<Vec<_>, _>>();
println!("{:?}", v);
let v = (1..10)
.map( |n| {
if n % 4 == 4 { // impossible
Err("Too fourish!")
}
else {
Ok(n)
}
}).collect::<Result<Vec<_>, _>>();
println!("{:?}", v);
}
Output:
Err("Too fourish!")
Ok([1, 2, 3, 4, 5, 6, 7, 8, 9])
More info: https://doc.rust-lang.org/std/result/enum.Result.html#implementations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With