Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

rust - 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`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

Instead, you can add in 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.

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

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...