Traits and Generics in Rust
by Hexagon, 3 min read rust guide
Traits describe what a type can do, and generics let you write code that works with any type that can do it. Together, they're how Rust shares behavior between types, instead of inheritance. Let's see how they fit together.
What's a Trait?
A trait is a set of methods that a type promises to have. If you've used interfaces in TypeScript or Java, it's a similar idea.
impl Describe for Dog reads as "implement the trait Describe for the type
Dog". The compiler checks that every method in the trait is there, with the
right signature.
Default Methods
A trait can provide a default implementation, which types can use as is, or replace:
;
;
English and Swedish are unit structs, with no fields. They exist only to
implement the trait.
Generics
Generics let you write a function once, for many types. You've used generic
types already: Vec<T>, Option<T> and Result<T, E>. Here's a generic
function:
<T: PartialOrd + Copy> declares a type parameter called T, and says what
T must be able to do. These are called trait bounds:
PartialOrdmeans that values can be compared with>.Copymeans that values can be copied out of the slice, as we do withlargest = items[0].
Without the bounds, the function wouldn't compile, as Rust can't know if any
random type supports >. This is the big difference from JavaScript: the
requirements are written down, and checked before the program runs.
Generic code is as fast as hand-written code. The compiler creates a separate
version of largest for each type it's used with.
Traits as Parameters
When a function just needs "something that implements a trait", there's a
shorter way to write it, with impl Trait:
;
// These two functions mean the same thing
When bounds get long, you can move them to a where clause:
use ;
Trait Objects
Generics are decided at compile time. Sometimes, you want a list of different
types that share a trait, decided at runtime. For that, use a trait object,
dyn Trait, usually inside a Box:
Box puts a value on the heap. That's needed here, as circles and squares have
different sizes, and a Vec needs all its items to be the same size. A Box is
always the size of a pointer.
When should you use what? If the set of types is fixed and known, an enum like
the Shape enum from the article about enums is often simpler. If other code
should be able to add its own types, use a trait.
Standard Traits
Much of the standard library is built on traits. These are the ones you'll meet most often:
Debug: printing with{:?}.Display: printing with{}.Clone: making copies with.clone().Copy: copied automatically instead of moved.PartialEqandEq: comparing with==.PartialOrdandOrd: comparing with<and>, and sorting.Hash: using the type as a key in aHashMap.Default: a default value, withType::default().FromandInto: converting between types.
Many of them can be derived, so the compiler writes the code for you:
Display can't be derived, as Rust can't guess how you want your type to look.
You implement it yourself, like we did for the error type in the article about
error handling:
use fmt;
From and Into
Implementing From lets you convert one type to another, and you get Into for
free:
;
;
From is also what the ? operator uses to convert errors. If you implement
From<ParseIntError> for your own error type, ? converts the error
automatically.
Conclusion
Traits are Rust's way to share behavior, and generics are the way to use that behavior without knowing the exact type. They take the place of both inheritance and the duck typing you might know from JavaScript, but checked by the compiler.
As an exercise, try implementing Display for the TrafficLight enum from the
article about enums, so that println!("{light}") prints the color in plain
words.