简体   繁体   English

Rust:有没有办法使用 map 缩短这个 if/else 代码?

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

I am having a hard time how to use map as shown in this:我很难使用 map,如下所示:

Why does Rust need the `if let` syntax? 为什么 Rust 需要 `if let` 语法?

Is there a way to shorten this code using map?有没有办法使用 map 缩短此代码? I need the else part to work too but not sure how to do it with map?我也需要else部分才能工作,但不确定如何使用 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())
    }
}

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 .如果要在None的情况下返回不同的值,可以使用Optionmap_or或其惰性版本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.如果您不想在None的情况下返回不同的值,而只想 map Option<T>Option<U> ,则可以使用.map()代替。

For more information on eager and lazy evaluation when deciding to use .map_or() or .map_or_else() the following might be of help:有关决定使用.map_or().map_or_else()急切惰性评估的更多信息,以下可能会有所帮助:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM