Skip Navigation

Where is the sort method implemented on Vec? (A surprisingly informative question to answer if you're learning rust)

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 the deref 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.
  • So sort() isn't implemented on Vec, it's implemented on the slice type ([T]).
  • But Vec implements Deref, substituting [T] for Vec<T> in all function/method calls.
  • Which means Vec gets all of the methods implemented on [T] ... almost like Vec is a subclass of [T]!
  • And yea, OOP people want to abuse this (see, eg, rust-unofficial on anti-patterns)
0
0 comments