本文介绍了为什么Option< String> .as_ref()不取消引用Option<& str&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期望这两个代码示例具有相同的结果:

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`

推荐答案

因为 Option::as_ref 已定义:

Because that's how Option::as_ref is defined:

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

由于您有Option<String>,所以生成的类型必须Option<&String>.

Since you have an Option<String>, then the resulting type must be Option<&String>.

相反,您可以添加 String::as_str :

Instead, you can add in String::as_str:

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

或更短:

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

最终,您还可以使用 Option::deref .

Eventually, you can also use Option::deref.

另请参阅:

这篇关于为什么Option&lt; String&gt; .as_ref()不取消引用Option&lt;&amp; str&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 20:17