Pre-RFC: Option<String> to Option<&str> [solved]

I find that I need to convert Option<String> to Option<&str> quite often. Simple option.as_ref() is not sufficient, because it gives Option<&String> which doesn't automagically deref.

The code for this is not terrible, but relatively long for an operation that seems basic: option.as_ref().map(|s| s.as_str()).

Could there be a better method for this? What would it be?

OK, there's Option::as_deref()

The most straightforward solution could be adding option.as_str() for Option<String>. I wouldn’t mind that, but it’s not generic (e.g. Option<Vec<T>> to Option<[T]> is left out).

However, I worry that more generic solutions would end up being blocked by either lack of specialization, or an overly generic as_ref() could risk breaking crates due to adding more ambiguity to type inference.

I too have needed this many times.

I think generally, you're looking for a shorthand for:

option.as_ref().map(Deref::deref)

And maybe also:

option.as_mut().map(DerefMut::deref_mut)

Bikeshed: as_deref, as_deref_mut?

1 Like
6 Likes

To add to that, here is the relevant documentation.

1 Like

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