Is there a way I can use map such that if a certain condition is met I can return an error? The reason is that i'm trying to implement the trait FromStr
for my struct BigNum
:
impl FromStr for BigNum {
fn from_str(s: &str) -> Result<BigNum, BigNum::Err> {
let filter_vec = t_num.chars().
map(|a| match a.to_digit(10) {
Some(x) => { x },
None => { /* return from function with Err */ }
});
}
}
Is this possible to do? Or should I simply iterate over the chars()
myself and return an error upon reaching a None
? Just wondering if there's an easy way to break out of map
and return from the function
Two key pieces of information will be useful here:
FromIterator
(which powers Iterator::collect
) is implemented for Result
as well.Since you didn't provide a MCVE, I made up sample code that can actually compile:
fn foo(input: &[u8]) -> Result<Vec<u8>, ()> {
input.iter().map(|&i| {
if i > 127 {
Err(())
} else {
Ok(i + 1)
}
}).collect()
}
fn main() {
let a = foo(&[1,2,3,4]);
let b = foo(&[200,1,2,3]);
println!("{:?}", a);
println!("{:?}", b);
}
If you stick a println!
in the map
body, you can see that no numbers are processed after the 200.
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