简体   繁体   English

为什么选择<String> .as_ref() 不解除对 Option&lt;&amp;str&gt; 的引用?

[英]Why does Option<String>.as_ref() not deref to Option<&str>?

I expect the same result for both of these code samples:我希望这两个代码示例的结果相同:

let maybe_string = Some(String::from("foo"));
let string = if let Some(ref value) = maybe_string { value } else { "none" };
let maybe_string = Some(String::from("foo"));
let string = maybe_string.as_ref().unwrap_or("none");

The second sample gives me an error:第二个示例给了我一个错误:

error[E0308]: mismatched types
 --> src/main.rs:3:50
  |
3 |     let string = maybe_string.as_ref().unwrap_or("none");
  |                                                  ^^^^^^ expected struct `std::string::String`, found str
  |
  = note: expected type `&std::string::String`
             found type `&'static str`

Because that's how Option::as_ref is defined:因为这就是Option::as_ref的定义方式:

impl<T> Option<T> {
    fn as_ref(&self) -> Option<&T>
}

Since you have an Option<String> , then the resulting type must be Option<&String> .由于您有一个Option<String> ,那么结果类型必须Option<&String>

Instead, you can add in String::as_str :相反,您可以添加String::as_str

maybe_string.as_ref().map(String::as_str).unwrap_or("none");

Or the shorter:或者更短的:

maybe_string.as_ref().map_or("none", String::as_str);

As of Rust 1.40, you can also use Option::as_deref .从 Rust 1.40 开始,您还可以使用Option::as_deref

maybe_string.as_deref().unwrap_or("none");

See also:另见:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM