Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from function upon condition met in map

Tags:

rust

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

like image 995
Syntactic Fructose Avatar asked Feb 10 '23 13:02

Syntactic Fructose


1 Answers

Two key pieces of information will be useful here:

  1. Iterators operate one item at a time, so iterator adaptors will only be executed while something is consuming the iterator.
  2. 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.

like image 162
Shepmaster Avatar answered Feb 19 '23 18:02

Shepmaster