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

Pra*_*y C 4 rust

我很难如何使用地图,如下所示:

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

有没有办法使用地图来缩短这段代码?我else也需要该部件才能工作,但不知道如何使用地图来实现?

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())
    }
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*son 5

如果您想在 的情况下返回不同的值None,可以使用Option\xe2\x80\x99smap_or或其惰性版本map_or_else

\n
fn the_answer(value: Option<u8>) -> String {\n    value.map_or(String::from("Not the answer"), |n| format!("{} is the answer!", n))\n}\n\nfn main() {\n    println!("{}", the_answer(Some(42)));\n    println!("{}", the_answer(None));\n}\n
Run Code Online (Sandbox Code Playgroud)\n

如果您不想在 的情况下返回不同的值None并且只想映射Option<T>Option<U>,则可以改用.map()

\n

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

\n\n