I expect same result for both 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:
expected type `&std::string::String`
found type `&'static str`
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);
Eventually, you can also use Option::deref
.
See also:
- Converting from Option<String> to Option<&str>