Rust Conversion traits Deref & DerefMut

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The std::ops::Deref and std::ops::DerefMut traits are used for overloading the dereference operator, *x. For types A and B,

impl Deref<Target=B> for A

indicates that dereferencing a binding of &A will yield a &B and,

impl DerefMut for A

indicates that dereferencing a binding of &mut A will yield a &mut B.

Deref (resp. DerefMut) also provides a useful language feature called deref coercion, which allows a &A (resp. &mut A) to automatically coerce to a &B (resp. &mut B). This is commonly used when converting from String to &str, as &String is implicitly coerced to &str as needed.


Note: DerefMut does not support specifying the resulting type, it uses the same type as Deref does.

Note: Due to the use of an associated type (unlike in AsRef), a given type can only implement each of Deref and DerefMut at most once.



Got any Rust Question?