&Option<String> to Option<&str>

Is there a more palatable way to go from &Option<String> to Option<&str> than .as_ref().map(|s| &s[..])? Do we need a

impl Option<T>
    fn as_deref(&self) -> Option<&<T as Deref>::Target>
    where T: Deref {
        self.as_ref().map(|t| t.deref())
    }
}
1 Like

.as_ref() would be enough, if coercions propagated through structs and enums.

Hmm. I suppose as_ref would also be enough if it looked like

    fn as_ref<U: ?Sized>(&self) -> Option<&U> where T: AsRef<U> {
        match *self {
            Option::Some(ref x) => Option::Some(x.as_ref()),
            Option::None => Option::None,
        }
    }

I realize AsRef appeared too close to 1.0 for this to have been considered. :disappointed:

Oh wait, looks like there’s no impl<T> AsRef<T> for T.

Note from the future: The as_deref method suggested here was added to Option in Rust 1.40.

4 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.