Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an alternative expression for match in Rust?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)?));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading