Rust: Is there a way to shorten this if/else code using map?

Viewed 890

I am having a hard time how to use map as shown in this:

Why does Rust need the `if let` syntax?

Is there a way to shorten this code using map? I need the else part to work too but not sure how to do it with map?

fn token(&self) -> Option<String> {
    if let Some(token) = actix_web::HttpMessage::cookie(self,"token") {
        Some(token.value().to_owned())
    } else {
        None
        //Some("NO COOKIE!!!!".to_owned())
    }
}
1 Answers

If you want to return a different value in the case of None, you can use Option’s map_or or its lazy version map_or_else.

fn the_answer(value: Option<u8>) -> String {
    value.map_or(String::from("Not the answer"), |n| format!("{} is the answer!", n))
}

fn main() {
    println!("{}", the_answer(Some(42)));
    println!("{}", the_answer(None));
}

If you do not want to return a different value in the case of None and only want to map Option<T> to Option<U>, you could use .map() instead.

For more information on eager and lazy evaluation when deciding to use .map_or() or .map_or_else() the following might be of help:

Related