Convert Option<&str> to Option<String>

What is a short way to get an owned Option from a Option<&str>?

fn main() {
    let a: Option<&str> = Some("a");
    let _b: Option<String> = a.map(|s| s.to_string());
    let _c: Option<String> = a.map(|s| s.into());
    let _d: Option<String> = a.map(Into::into);
    let _e: Option<String> = a.map(ToOwned::to_owned);
    let _f: Option<String> = a.map(String::from);
}

Playground

17 Likes

Is there a preference, what style is most idiomatic?

I think it's more personal preference than anything (pretty sure I've seen all of those examples in other people's code at least once!), but I'd usually go for _f:

  • _b is longer and requires an explicit closure.
  • _c and _d don't work without type annotations (unless they're in a context where the compiler can infer what type you mean).
  • _e and _f don't have either of those trade-offs, but the latter makes it a bit clearer what you're actually mapping the contents of a to.
10 Likes

Thank you very much!

I wish just like there is cloned (Option in std::option - Rust), there would be owned.

3 Likes

You might be interested in What is the idiomatic way to convert &str to String?