176. Option::as_deref — Stop Writing .as_ref().map(|s| s.as_str())
You have an Option<String>. The function next door takes Option<&str>. The chain you keep typing — .as_ref().map(|s| s.as_str()) — has a one-method replacement.
The pattern that keeps showing up
Borrowing the inside of an Option<String> looks like this:
| |
as_ref() turns Option<String> into Option<&String>, then map reaches inside to pull out &str. Two methods, one closure, all just to borrow.
Option::as_deref collapses the whole thing:
| |
Same result, one call, no closure.
Why it works
as_deref is defined for any Option<T> where T: Deref. It calls Deref::deref on the inner value, so you get Option<&T::Target>:
| |
Anything that derefs works, including your own types — implement Deref and as_deref follows for free.
Where it actually saves you
The most common use is feeding a borrowed view into a function that wants the unsized form:
| |
The stored value stays untouched — as_deref only borrows.
There’s also as_deref_mut for the &mut version, and Result::as_deref / as_deref_mut for the same trick on Result:
| |
Takeaway
Whenever you catch yourself typing .as_ref().map(|x| x.as_str()) or .as_ref().map(|x| &**x), reach for .as_deref(). One method, no closure, and it works on anything that derefs.