【问题标题】:Is there a more elegant way to unwrap an Option<Cookie> with a default string?有没有更优雅的方法来用默认字符串解开 Option<Cookie> ?
【发布时间】:2026-02-05 21:50:02
【问题描述】:

我想打开 cookie 或返回一个空的 &amp;str None

let cookie: Option<Cookie> = req.cookie("timezone");

// right, but foolish:
let timezone: String = match cookie {
    Some(t) => t.value().to_string(),
    None => "".into(),
};

这是一个错误:

let timezone = cookie.unwrap_or("").value();

【问题讨论】:

  • 您不能在&amp;str 上致电.value()。你这样做的方式是正确的;为什么你认为它“愚蠢”?
  • @anunaki 类型必须兼容unwrap_or 才能工作,所以为了cookie.unwrap_or(thing)thing 必须是Cookie,而不是str。但是,您可以先映射Cookie::value 以获取Option(&amp;str),然后再映射unwrap_or,这样类型是兼容的。这基本上就是 map_or / map_or_else 一步完成的。

标签: rust option unwrap


【解决方案1】:

您可以使用unwrap_or_default 加上map,您想要提取一个String 值,如果无法完成,则使用默认值。订单很重要:

let timezone: String = cookie.map(|c| c.value().to_string()).unwrap_or_default();

Playground

【讨论】:

  • 这里甚至不需要类型注释,因为to_string() 对返回类型没有任何疑问。
最近更新 更多