【发布时间】:2026-02-05 21:50:02
【问题描述】:
我想打开 cookie 或返回一个空的 &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();
【问题讨论】:
-
您不能在
&str上致电.value()。你这样做的方式是正确的;为什么你认为它“愚蠢”? -
@anunaki 类型必须兼容
unwrap_or才能工作,所以为了cookie.unwrap_or(thing),thing必须是Cookie,而不是str。但是,您可以先映射Cookie::value以获取Option(&str),然后再映射unwrap_or,这样类型是兼容的。这基本上就是map_or/map_or_else一步完成的。