Is there an alternative expression for match in Rust?

Viewed 84

I know that when handling errors using Result and Option, it can be expressed more concisely by using unwrap_or_else, unwrap_or_default, etc. instead of match.

The following is an example of expressing the match expression more concisely using unwrap.

let engine_name = match config.engine_name {
    Some(name) => name,
    None => host_name.clone(),
};

->
let engine_name = config.engine_name
    .unwrap_or_else(|| host_name.clone());


let group_name = match config.group_name {
    Some(name) => name,
    None => String::from("")
};
->
let group_name = config.group_name.unwrap_or_default();

Questions

Is there a function I can use instead of match if I want to put a return statement instead of putting a different value when an error occurs?

let accept_service = ServiceBuilder::new().service(match AcceptService::new() {
    Ok(service) => service,
    Err(e) => return Err(format!("failed to bind server socket: {}", e).into()),
});
1 Answers

You can use a combination of map_err() and the error propagation operator ?:

ServiceBuilder::new()
    .service(AcceptService::new().map_err(|e| format!("failed to bind server socket: {}", e)?));
Related