What's the mean of AsRef must not fail?

In the document of the trait AsRef, there is one sentense:

Note: this trait must not fail. If the conversion can fail, use a dedicated method which returns an Option or a Result<T, E>.

Then what does it mean "must not fail"? What if it fails, can the compiler find out and deny to compile it? Or it compiles, and cause runtime error?

In the case of AsRef, really the only possible mode of failure is panicking. So to users it means "you may assume this does not panic," and to implementors it means "pretty pretty please do not let this function panic because users will find that very surprising."

Nothing is truly stopping you, however, from writing an implementation that panics.

7 Likes

Another thing that comes to mind is you can't implement AsRef<str> for something like Option<&str>, because you won't always be able to get the str by reference.

You could map None to "", or any other &'static str that makes sense in your context.

(I'm sure we'd never do AsRef<str> for Option<&str> this way, but you could for a newtype.)