Using unwrap_or_else for error handling in Rust

Viewed 336

I have a rust program that has a function ‘is_input_sanitized’ that takes an input String m, and checks if the input is free of special characters.The method is being used on a separate function in the following way.

let a = match is_input_sanitized(m) {
  Ok(m) => m,
  Err(_) => { return Err("error"); },
};

I am trying to convert this snippet into using ‘unwrap_or_else’ which will return an error when the input is not sanitized.I have read the documentation and have not been able to decipher a proper way to achieve this. Is this conversion possible?

1 Answers

unwrap_or_else is for extracting Result values. It sounds to me like you don't want to extract the result, so much as make a new one and propagate errors. You have two different things you want to do here. The first is that you want to change the error from whatever it started as (indicating by your _ in the pattern match) to something you control, and the second is that you want to return errors.

Replacing the error can be done with map_err, which takes a function (such as a closure) and applies that function to the error if the Result is an Err. If the result is Ok, then it returns the current Result unmodified.

The second problem, returning on Err, is exactly what the question mark operator was invented for.

Chaining results using match can get pretty untidy; luckily, the ? operator can be used to make things pretty again. ? is used at the end of an expression returning a Result, and is equivalent to a match expression, where the Err(err) branch expands to an early return Err(From::from(err)), and the Ok(ok) branch expands to an ok expression.

So what you're looking for is

let a = is_input_sanitized(m).map_err(|_| "error")?;
Related