我很难如何使用 map ,如下所示:
Why does Rust need the `if let` syntax?
有没有办法使用 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
的情况下返回不同的值,您可以使用 Option
的 map_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
的情况下返回不同的值并且只想映射Option<T>
至 Option<U>
,您可以使用 .map()
反而。有关决定使用
.map_or()
时的急切和惰性求值的更多信息或 .map_or_else()
以下内容可能会有所帮助:关于Rust:有没有办法使用 map 缩短这个 if/else 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65913261/