Printing default strings, Option<String> and unwrap_or("foo"), String / &str coercion

Hi,

I am trying to format (log/print) an Option<String>, or an alternative value if the Option is None. I am basically running into the same thing as this thread from 2016: &Option<String> to Option<&str>

I am wondering if anything has changed since then? The way I've found to appease the compiler is still pretty ugly:

log::error!("foo {}",
  myoption.map(|s| &s as _).unwrap_or("none-case string"));

Or perhaps more horrifically,

log::error!("foo {}",
  (myoption.into() as Option<&str>).unwrap_or("none-case string"));

What's idiomatic? Thanks.

You can use the new Option::as_deref method added in Rust 1.40:

log::error!("foo {}", myoption.as_deref().unwrap_or("none-case string"));
2 Likes

Great, thanks! I saw the API but did not expect Deref on String to yield &str (I'm coming from a C background).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.