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
Deref
docs, especially thederef coercion
part - 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
self
in method calls.- And obviously requires that
Deref
be implemented.
- And obviously requires that
- So
sort()
isn’t implemented onVec
, it’s implemented on theslice
type ([
). ] - But
Vec
implementsDeref
, substituting[
for ]Vec<T>
in all function/method calls. - Which means
Vec
gets all of the methods implemented on[
… almost like ]Vec
is a subclass of[
! ] - And yea, OOP people want to abuse this (see, eg, rust-unofficial on anti-patterns)
You must log in or register to comment.