You’ve gotta be familiar with Traits to try to work this out.
Just in case you want to try to work it out your self first
Gotta say, after hearing that rust is not an OOP/Class-inheritance language, and is strongly and explicitly typed, the Deref trait feels like a helluva drug!
Obviously it’s not the same thing, but working this out definitely had me making a couple of double takes.
Somewhat awkwardly, I worked it out through the standard lib docs before reading ch 15 of the book (it’s more fun this way!).
And for those who want a quick answer:
- Read the
Derefdocs, especially thederef coercionpart - This allows a variable of a particular type to be implicitly substituted with another variable of a different type.
- It happens any time a reference is passed in/out of a function, including
selfin method calls.- And obviously requires that
Derefbe implemented.
- And obviously requires that
- So
sort()isn’t implemented onVec, it’s implemented on theslicetype ([]). - But
VecimplementsDeref, substituting[]forVec<T>in all function/method calls. - Which means
Vecgets all of the methods implemented on[]… almost likeVecis a subclass of[]! - And yea, OOP people want to abuse this (see, eg, rust-unofficial on anti-patterns)
You must log in or # to comment.

