Returning a value from a map() function

i have a Vec, where i need to match the value of the string to specific other strings, in order to match each and every one of them, i decided to use Vec.iter().map(...) to solve this issue (and also since i want to use rayon in that project). here is some example code to explain what i mean:

use thiserror::Error; // 1.0.48

#[derive(Debug, Clone, PartialOrd, PartialEq)]
pub enum SomeError {
    #[error("some error data {0}")]

fn main(){
    let Vector = Vec::new();
    for _ in 0..100{Vector.push("foo");}
    let Vector = Vector.iter().map(|value|{
        match value{
            &"foo" => "bar",
            &"bar" => "foo",
            _ => return SomeError::ExampleError(String::from("unknown value")),

if you tried this code in the rust playground, you'd see it returns

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/
17 | /         match value{
18 | |             &"foo" => "bar",
19 | |             &"bar" => "foo",
20 | |             _ => return SomeError::ExampleError(String::from("unknown value")),
21 | |         }
   | |_________^ expected `SomeError`, found `&str`
note: return type inferred to be `SomeError` here
  --> src/
20 |             _ => return SomeError::ExampleError(String::from("unknown value")),
   |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` (bin "playground") due to previous error

i don't want to return the value in _ into the match function, i want to return that value to the actual function, so, how can i return a value from the map() function directly into the function using it, not to the variable?

There are many ways to do it. But it all depends on what you'll do with errors. Like and

map takes a closure and return inside a closure can only return from this closure. If you want an iterator you can start producing values of type Result inside of it and then do something like .collect::<Result<Vec<Item>, Error>>() at the end. Alternatively you can use for xxx in yyy.

You can't. return always returns from the innermost function. (Doing anything else would be egregiously confusing.)

Fortunately, as others have pointed out, an iterator yielding Results can exhibit the exact short-circuiting behavior that you want, by means of the appropriate methods that consume it (e.g. try_fold() or collect()).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.