Is there to_owned for Options?


Hi! What’s the best way to convert Option<&str> into Option<String>?

to_owned does not work, because it is not a reference. .cloned does not work because it does not changes the type.

.map(str::to_owned) works, but is not pretty :frowning:


I can’t see any other way to do it currently :frowning:

It seems like Option should probably have an implementation of ToOwned, but the associated type constraints stop it from working, type Owned: Borrow<Self> is impossible for Option to implement.

But, like the .as_ref inherent method that is almost but not quite the same as the AsRef trait, Option could have an alternative added, hiding the ugliness away

impl<'a, T> Option<&'a T> where T: ToOwned {
    fn to_owned(&self) -> Option<T::Owned> {


Yeah, I was thinking that maybe perhaps this method is missing… I wonder if someone should send a PR to rust :wink:


I would argue that the map is exactly what you want, and isn’t long enough to justify its own method. Plus, option is a type with ownership, so to_owned isn’t appropriate on it; you’d want inner_to_owned or something.