Deref Traits
Dereftrait is used for immutable dereferncing operation.
pub trait Deref {
type Target: ?Sized;
// Required method
fn deref(&self) -> &Self::Target;
}
-
Deref coercion: iff
T: Deref<Target = U>andlet v: T*vis equivalent to*Deref::deref(&v)(immutable contexts)- values of type
&Tare coerced to values of type&U Timplicitly implements all the methods of theUwhich take the&selfreceiver
-
Using with
Option<Box<T>>
v: Option<Box<T>>
v.as_ref(): Option<&Box<T>>
v.as_deref(): Option<&T>
pub const fn as_ref(&self) -> Option<&T>
pub fn as_mut(&mut self) -> Option<&mut T>
pub fn as_deref(&self) -> Option<&<T as Deref>::Target>
pub fn as_deref_mut(&mut self) -> Option<&mut <T as Deref>::Target>
pub fn as_pin_ref(self: Pin<&Option<T>>) -> Option<Pin<&T>>
pub fn as_slice(&self) -> &[T]
pub fn as_mut_slice(&mut self) -> &mut [T]
-
Strings! →Deref<Target = str> -
Stringexposesas_str()throughDeref, which is why you can call allstrmethods on aString.Derefexposes the string slice through the a bit awkward&*ssyntax, so another way to obtainOption<&str>isopt.as_ref().map(|s| &*s). This will work in generic code whereas_str()is not available. -
Option::as_deref()is a short-hand for that - called onOption<String>, it will returnOption<&str>. Called onOption<Vec<u8>>will returnOption<&[u8]>, and so on.