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> =|s| s.to_string());
    let _c: Option<String> =|s| s.into());
    let _d: Option<String> =;
    let _e: Option<String> =;
    let _f: Option<String> =;



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.

Thank you very much!

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


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