Kuly14
Kuly14

Reputation: 608

How to return a Custom Error from inside a closure | Rust

I have a closure that looks like this:

pub fn getBytes(bytes: Vec<String>) -> Result(String, InputError) {
    bytes.iter().for_each(|byte| {
        let mut fixed_byte = String::new();
        if byte.contains("0x") {
            fixed_byte = dict::add_push(byte);
            if fixed_byte.trim() == String::from("Wrong length") {
                return Err(InputError::WrongHexLength(byte.to_string())); // Problem is here
            }
        }
        bytecode.push_str(&fixed_byte);
    });
    Ok(bytecode)
}

And I want to return a custom error, but since it's inside a closure I get an error like this:

mismatched types
   --> src/lib.rs:110:24
    |
110 |                 return Err(InputError::WrongHexLength(byte.to_string()))
;
    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 expected `()`, found enum `Result`
    |
    = note: expected unit type `()`
                    found enum `Result<_, InputError>`

How can I terminate what the closure does and just return the error?

Thanks!

Upvotes: 1

Views: 125

Answers (1)

Aleksander Krauze
Aleksander Krauze

Reputation: 6255

Use try_for_each. As documentation says:

An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error.

Alternatively use for loop and more imperative approach instead of functional for_each.

Upvotes: 1

Related Questions