我很难如何使用地图,如下所示:
有没有办法使用地图来缩短这段代码?我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)
如果您想在 的情况下返回不同的值None,可以使用Option\xe2\x80\x99smap_or或其惰性版本map_or_else。
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}\nRun Code Online (Sandbox Code Playgroud)\n如果您不想在 的情况下返回不同的值None并且只想映射Option<T>到Option<U>,则可以改用.map()。
有关在决定使用时急切和惰性评估的更多信息.map_or(),或者.map_or_else()以下内容可能会有所帮助: