繁体   English   中英

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

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

我很难使用 map,如下所示:

为什么 Rust 需要 `if let` 语法?

有没有办法使用 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())
    }
}

如果要在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));
}

如果您不想在None的情况下返回不同的值,而只想 map Option<T>Option<U> ,则可以使用.map()代替。

有关决定使用.map_or().map_or_else()急切惰性评估的更多信息,以下可能会有所帮助:

暂无
暂无

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

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