是否有更优雅的方法来使用默认字符串解开 Option<Cookie> ?

Anu*_*aki 6 rust option-type

我想打开 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(),
};
Run Code Online (Sandbox Code Playgroud)

这是一个错误:

let timezone = cookie.unwrap_or("").value();
Run Code Online (Sandbox Code Playgroud)

Net*_*ave 5

您可以使用unwrap_or_defaultplus map,您想要的是提取一个String值,如果不能完成,则使用默认值。订单事宜:

let timezone: String = cookie.map(|c| c.value().to_string()).unwrap_or_default();
Run Code Online (Sandbox Code Playgroud)

操场