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

标签 rust

我很难如何使用 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()以下内容可能会有所帮助:
  • What is the difference between “context” and “with_context” in anyhow?
  • 关于Rust:有没有办法使用 map 缩短这个 if/else 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65913261/

    相关文章:

    rust - 重新分配应该是循环中可变借用的不可变变量

    process - 如何在不阻塞Rust的情况下读取子进程的输出?

    rust - 为什么不能在同一结构中存储值和对该值的引用?

    multithreading - 如何在线程之间共享对 AtomicBool 的访问?

    rust - 索拉纳 anchor : how can a program check approved token allowance given by an user?

    rust - 穷举整数匹配

    memory - 为什么在Rust中 “capture by reference”与 “capture a reference by value”等效?

    rust - 将条目添加到 HashMap 并在 for 循环中获取对它们的引用

    path - 如何替换PathBuf或Path的文件扩展名?

    function - 我可以有一个在 Rust 中不被类型化为闭包的匿名函数吗?