[英]Why is String -> &str different in the impl for Deref and AsRef?
[英]Why does Option<String>.as_ref() not deref to Option<&str>?
我希望這兩個代碼示例的結果相同:
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");
第二個示例給了我一個錯誤:
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
的定義方式:
impl<T> Option<T> {
fn as_ref(&self) -> Option<&T>
}
由於您有一個Option<String>
,那么結果類型必須是Option<&String>
。
相反,您可以添加String::as_str
:
maybe_string.as_ref().map(String::as_str).unwrap_or("none");
或者更短的:
maybe_string.as_ref().map_or("none", String::as_str);
從 Rust 1.40 開始,您還可以使用Option::as_deref
。
maybe_string.as_deref().unwrap_or("none");
另見:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.