4

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

1
  • Did you try return Err(..whatever..)? Commented Jul 19, 2015 at 23:47

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.