Lesson 11
Generics and Traits
You have already seen one generic type: Option<T> works the same way whether T is a number or a piece of text. This lesson covers how to write your own generic functions and structs, and how a trait lets a generic function say what a type must be able to do, without saying which type it is.
Generic Functions
Suppose you need the largest number in a slice, for both i32 and f64. Without generics, you write the same function twice.
fn largest_i32(list: &[i32]) -> i32 {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
fn largest_f64(list: &[f64]) -> f64 {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
The two functions differ only in one word, i32 against f64. A generic function replaces that word with a type parameter, a stand-in name for a type the caller chooses. <T> right after the function name declares T as that stand-in name.
fn largest<T>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
This does not compile. T could stand for anything at all, including a type that has no order and no greater-than. The compiler will not let the function body write item > largest until it knows every type the caller might choose actually supports >.
error[E0369]: binary operation `>` cannot be applied to type `T`
--> src/main.rs:4:17
|
4 | if item > largest {
| ---- ^ ------- T
| |
| T
|
help: consider restricting type parameter `T` with trait `PartialOrd`
|
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> T {
| ++++++++++++++++++++++
PartialOrd is the trait that gives a type the <, >, <=, and >= operators. Writing T: PartialOrd after the type parameter is a trait bound: a requirement that narrows “any type at all” down to “any type that implements PartialOrd”. With that bound in place, the compiler knows item > largest is legal, because every type the function will ever be called with is guaranteed to support it.
fn largest<T: PartialOrd>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
This still does not compile, for a different reason.
error[E0508]: cannot move out of type `[T]`, a non-copy slice
--> src/main.rs:2:23
|
2 | let mut largest = list[0];
| ^^^^^^^
| |
| cannot move out of here
| move occurs because `list[_]` has type `T`, which
| does not implement the `Copy` trait
error[E0507]: cannot move out of a shared reference
--> src/main.rs:3:18
|
3 | for &item in list {
| ---- ^^^^
| |
| data moved here because `item` has type `T`, which does not
| implement the `Copy` trait
-
listis a borrowed slice,&[T]. The function does not own the values inside it, only a reference to them. -
list[0]and the pattern&itemboth try to pull a value of typeTout of that borrow and into a variable the function owns. For a type such asStringorVec, that is exactly the kind of move that ownership rules forbid: the borrowed slice does not own its values, so it cannot give one away. -
A type such as
i32orf64has no such problem. It is a small, fixed-size value with nothing on the heap, so Rust can make a second copy of it just by copying its bits, leaving the original completely untouched. A type marked with theCopytrait is a promise that copying it this way is always safe. -
T: Copytells the compiler that whatever type the caller chooses, reading a value out of the slice may copy it instead of moving it. That is what makeslist[0]and&itemlegal.
Adding both bounds, joined with +, compiles and runs.
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![14, 8, 27, 3];
let floats = vec![1.5, 9.2, 4.4];
println!("largest number: {}", largest(&numbers));
println!("largest float: {}", largest(&floats));
}
largest number: 27
largest float: 9.2
-
+betweenPartialOrdandCopyjoins two trait bounds into one requirement:Tmust implement both. A type parameter can carry as many bounds as the function body needs. -
You never write
largest::<i32>(&numbers)yourself here. Rust works outTfrom the argument you pass, the same way it works out the type of a variable from the value you give it. -
The compiler builds a separate, ordinary version of
largestfor every type it is actually called with, one fori32and one forf64in this program. Calling a generic function costs nothing extra at run time compared to writinglargest_i32andlargest_f64by hand.
A Function with Two Type Parameters
A function can take more than one type parameter. Give each one its own letter, separated by commas.
fn describe_pair<A: std::fmt::Debug, B: std::fmt::Debug>(a: A, b: B) {
println!("{a:?} and {b:?}");
}
fn main() {
describe_pair(7, "seven");
describe_pair(3.5, true);
}
7 and "seven"
3.5 and true
-
println!can only print a value whose type promises it can be turned into text.std::fmt::Debugis the trait that makes that promise for output meant to help a programmer inspect a value, and{:?}is the format specifier that calls it, in place of the plain{}you have used for numbers and strings. -
Almost every built-in type implements
Debug, including&strandbool, which is why it is a common bound on a type parameter that a function only needs to print.
A and B do not have to be the same type. The first call uses i32 for A and &str for B; the second uses f64 and bool. Each is worked out independently from the argument in that position.
Generic Structs and Enums
A struct can take a type parameter too, so the same struct definition holds more than one kind of value.
struct Pair<T> {
first: T,
second: T,
}
fn main() {
let numbers = Pair { first: 3, second: 8 };
let words = Pair { first: String::from("up"), second: String::from("down") };
println!("{} and {}", numbers.first, numbers.second);
println!("{} and {}", words.first, words.second);
}
3 and 8
up and down
Pair<T> declares one type parameter, used for both fields. numbers fixes T to i32; words fixes it to String. Each value of Pair still holds two fields of the same type as each other, but two different Pair values can disagree about which type that is.
A struct does not have to use its type parameter on every field. Here label is always a String, and only value changes type.
struct Labeled<T> {
label: String,
value: T,
}
fn main() {
let score = Labeled { label: String::from("score"), value: 42 };
println!("{}: {}", score.label, score.value);
}
score: 42
An impl block on a generic struct repeats the type parameter right after impl, so the methods inside know what T means.
struct Pair<T> {
first: T,
second: T,
}
impl<T> Pair<T> {
fn new(first: T, second: T) -> Pair<T> {
Pair { first, second }
}
}
fn main() {
let numbers = Pair::new(3, 8);
println!("{} and {}", numbers.first, numbers.second);
}
3 and 8
An enum takes a type parameter the same way. You have already used two: Option<T> holds Some(T) or None, and Result<T, E> holds Ok(T) or Err(E). Both are ordinary enums, generic over the types they carry, defined in the standard library rather than by you.
Traits
A trait names a set of methods a type promises to provide. It looks like a struct’s impl block with the bodies left out.
trait Summary {
fn summary(&self) -> String;
}
struct Article {
headline: String,
body: String,
}
impl Summary for Article {
fn summary(&self) -> String {
format!("{}: {} characters", self.headline, self.body.len())
}
}
fn main() {
let article = Article {
headline: String::from("Rain expected"),
body: String::from("Showers are expected across the region today."),
};
println!("{}", article.summary());
}
Rain expected: 45 characters
-
trait Summary { fn summary(&self) -> String; }declares a method with no body, only its name and signature. Any type that implementsSummarymust supply that body itself. -
impl Summary for Article { ... }is whereArticlesupplies it. The method signature must match the one in the trait exactly. -
Once
ArticleimplementsSummary,article.summary()is called the same way as any other method.
A second type can implement the same trait with a completely different method body. This is the point of a trait: two unrelated types agree to answer the same call in their own way.
trait Summary {
fn summary(&self) -> String;
}
struct Article {
headline: String,
}
impl Summary for Article {
fn summary(&self) -> String {
format!("article: {}", self.headline)
}
}
struct Tweet {
handle: String,
text: String,
}
impl Summary for Tweet {
fn summary(&self) -> String {
format!("@{}: {}", self.handle, self.text)
}
}
fn main() {
let article = Article { headline: String::from("Rain expected") };
let tweet = Tweet { handle: String::from("wxwatch"), text: String::from("rain today") };
println!("{}", article.summary());
println!("{}", tweet.summary());
}
article: Rain expected
@wxwatch: rain today
Trait Bounds on a Generic Function
A trait bound, seen earlier with PartialOrd, is how a generic function requires the type it is called with to implement a trait. This lets the function call that trait’s methods, without knowing which concrete type it will run on.
trait Summary {
fn summary(&self) -> String;
}
struct Article {
headline: String,
}
impl Summary for Article {
fn summary(&self) -> String {
format!("article: {}", self.headline)
}
}
fn print_summary<T: Summary>(item: &T) {
println!("{}", item.summary());
}
fn main() {
let article = Article { headline: String::from("Rain expected") };
print_summary(&article);
}
article: Rain expected
print_summary does not mention Article anywhere. It works for Article, Tweet, or any other type, as long as that type implements Summary. The bound T: Summary is what makes item.summary() legal to write: without it, the compiler would not know that whatever T turns out to be has a summary method at all.
where writes the same bound after the function signature instead of inside the angle brackets. This reads better once a function has several type parameters or several bounds.
fn print_summary<T>(item: &T)
where
T: Summary,
{
println!("{}", item.summary());
}
Both forms mean exactly the same thing to the compiler. Use where when the bound list next to <T: ...> would otherwise run long.
Default Implementations
A trait method can have a body of its own, one that a type uses unless it writes a different one. This is a default implementation.
trait Summary {
fn topic(&self) -> String;
fn summary(&self) -> String {
format!("read more about {}", self.topic())
}
}
struct Article {
headline: String,
}
impl Summary for Article {
fn topic(&self) -> String {
self.headline.clone()
}
}
fn main() {
let article = Article { headline: String::from("rain") };
println!("{}", article.summary());
}
read more about rain
-
topichas no body in the trait, soArticlemust supply one, exactly as before. -
summarydoes have a body.impl Summary for Articlenever mentionssummaryat all, and callingarticle.summary()still works: it runs the default body from the trait. -
The default body can call other methods of the same trait, here
self.topic(), even though it does not know which typeselfwill turn out to be. It only knows that type implementsSummary, sotopicis guaranteed to exist.
A type can still override a default by writing its own body for that method inside its impl block. Whichever body a type writes for itself is the one that runs for that type.
impl Summary for Article {
fn topic(&self) -> String {
self.headline.clone()
}
fn summary(&self) -> String {
format!("breaking: {}", self.headline)
}
}
Now article.summary() runs this body instead of the trait’s default one. A default implementation is a starting point every type gets for free, not a rule every type is forced to follow.
Supertraits
A trait can require that any type implementing it also implements another trait first. The required trait is called a supertrait.
use std::fmt::Display;
trait Summary: Display {
fn summary(&self) -> String {
format!("about: {self}")
}
}
struct Article {
headline: String,
}
impl Display for Article {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.headline)
}
}
impl Summary for Article {}
fn main() {
let article = Article { headline: String::from("rain") };
println!("{}", article.summary());
}
about: rain
-
trait Summary: Displaymeans any type that implementsSummarymust also implementDisplay, the trait that controls how{self}prints a value inside aformat!string. -
Displayrequires exactly one method,fmt, and its signature never changes:&self, a&mut std::fmt::Formatter, and a return type ofstd::fmt::Result.Formatteris the buffer the final text is built into.fmt::ResultisOk(())on success, the sameResultyou have already seen used for work that can fail. -
write!(f, "{}", self.headline)works likeprintln!, but it writes the formatted text into the destination given as its first argument, heref, instead of printing straight to the terminal. -
Because
Displayis guaranteed, the default body ofsummarycan write{self}directly. It relies on a method it did not define itself, the same way a struct’s method can rely on another method of the same struct. -
impl Summary for Article {}is empty.Articlealready implementsDisplayabove it, andsummaryhas a default body, so there is nothing left to write. -
Leaving out
impl Display for Articlefirst would not compile. The compiler checks the supertrait is implemented before it lets you implementSummaryat all.
Trait Objects and dyn Trait
Every generic function you have written so far is compiled into a separate copy for each type it is called with, decided while the program is compiled. This is static dispatch: which method body runs is fixed before the program starts. Sometimes you need one collection that holds several different types together, as long as they all implement the same trait. A generic type parameter cannot do this, because a single Vec<T> can only hold one concrete type.
trait Summary {
fn summary(&self) -> String;
}
struct Article {
headline: String,
}
impl Summary for Article {
fn summary(&self) -> String {
format!("article: {}", self.headline)
}
}
struct Tweet {
text: String,
}
impl Summary for Tweet {
fn summary(&self) -> String {
format!("tweet: {}", self.text)
}
}
fn main() {
let items: Vec<Box<dyn Summary>> = vec![
Box::new(Article { headline: String::from("Rain expected") }),
Box::new(Tweet { text: String::from("rain today") }),
];
for item in &items {
println!("{}", item.summary());
}
}
article: Rain expected
tweet: rain today
-
dyn Summarymeans “some type that implementsSummary, not known until the program runs”. It is a trait object: a value the compiler agrees to callsummaryon, without knowing in advance whether it is holding anArticleor aTweet. -
dyn Summaryhas no fixed size, because anArticleand aTweetare not the same number of bytes.Box<dyn Summary>stores the value on the heap and keeps only a pointer to it inline, the same reason a recursive struct needs aBoxaround one of its fields. -
Vec<Box<dyn Summary>>is one vector holding several different types, as long as each one implementsSummary. This is exactly what a genericVec<T>cannot do. -
Calling
item.summary()inside the loop is dynamic dispatch: the program checks, while it is running, which typeitemis actually holding, and calls that type’s ownsummary. The generic version worked the opposite way: the compiler already knew the type before the program started, so no check is needed while it runs.
Key idea
A generic function such as
largest<T: PartialOrd>produces one compiled copy per type it is used with, and pays nothing extra while the program runs. A trait object such asBox<dyn Summary>produces one shared copy that works for every type at once, at the cost of one check, while the program runs, to find the right method body. Prefer a generic type parameter when the type is known and fixed at each call site. Reach fordyn Traitonly when you need a single collection, or a single variable, that holds more than one concrete type at once.
Reference
| Written as | What it does |
|---|---|
| fn f<T>(x: T) | A generic function, with T standing for any type. |
| fn f<T: Trait>(x: T) | A trait bound: T must implement Trait. |
| where T: Trait | The same bound, written after the signature. |
| struct S<T> { … } | A generic struct, holding a value of type T. |
| impl<T> S<T> { … } | Methods for every T a generic struct is used with. |
| trait Trait { … } | Names methods a type must, or by default does, provide. |
| impl Trait for S { … } | Supplies a trait’s methods for one struct or enum. |
| trait A: B { … } | A supertrait: implementing A requires B too. |
| dyn Trait | Some type implementing Trait, chosen while running. |
| Box<dyn Trait> | A trait object stored on the heap, behind a pointer. |
Check what stuck
The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →