Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
-
In short, do NOT implement the
Deref
trait unless you are absolutely sure that it's needed! According to Rust Official Doc - Deref, Deref should only be implemented for smart pointers. The Rust Programing Language book has a chapter covering smart pointers , however, the definition is vague. In the context of implementingDeref
for smart pointers, smart pointers are types that act like pointers but are not supposed to have methods on their own (so ambiguity during method resolution are avoid). For example,Box
implementsDeref
so that you can conveniently use methods of the target type. But if you look at the documentation ofBox
, the things you can do with the Box itself, likeBox::leak
, are non-method functions. This means that you always have to qualify them, likeBox::leak(my_box)
. -
If you do implement
Deref<Target = U>
on a typeT
, and it proved necessary to implement a generic traitTrait<S>
onT
. Then one should ensure that the implementations ofTrait<S>
for different parametersS
are not scattered acrossT
andU
. Put simply, eitherT
orU
should host all existingTrait<S>
implementations. Note that the preceding "or" is inclusive, meaning that bothT
andU
can host someTrait<S>
implementations, as long as they both host all of them.