Traits and Generics
Part 1 · Rust. Learn how traits describe shared behaviour, how generics let one function work with many types, and how From, Into and Display fit in.
Welcome to the bridge between Core Rust and Laravel Rust. Over the next five lessons we will learn the Rust features that web code leans on most. We start with two big ideas: traits and generics.
At the Rusty Bean Café, a latte and a croissant are very different things. But a till does not care: it only wants to know “what is your name?” and “what do you cost?”. Traits let us write that promise down once, and generics let us write code that works with anything that keeps the promise.
Traits: a promise of behaviour
A trait is a list of things a type can do. It is like a job description: “anyone who wants this job must be able to give a name and a price.”
trait Sellable { fn name(&self) -> String; fn price_cents(&self) -> u32;}
struct Latte { size: String,}
struct Croissant;
impl Sellable for Latte { fn name(&self) -> String { format!("{} latte", self.size) } fn price_cents(&self) -> u32 { 450 }}
impl Sellable for Croissant { fn name(&self) -> String { String::from("Croissant") } fn price_cents(&self) -> u32 { 325 }}
fn main() { let latte = Latte { size: String::from("large") }; println!("{} costs {} cents", latte.name(), latte.price_cents()); println!("{} costs {} cents", Croissant.name(), Croissant.price_cents());}large latte costs 450 centsCroissant costs 325 centsStep by step:
trait Sellable { ... }declares the promise. The functions have a signature but no body.impl Sellable for Lattesays “Lattekeeps this promise” and fills in the bodies.- We do the same for
Croissant. Each type can behave differently. - Now both types have
.name()and.price_cents(), just like ordinary methods.
Note
If you forget a function that the trait requires, the compiler stops you with error[E0046]: not all trait items implemented, missing: `price_cents` . The promise must be kept in full.
Default methods
A trait can include a ready-made body. Types get it for free and can override it if they want.
trait Sellable { fn name(&self) -> String; fn price_cents(&self) -> u32;
fn label(&self) -> String { format!("{}: ${}.{:02}", self.name(), self.price_cents() / 100, self.price_cents() % 100) }}label is built from the two required methods, so any Sellable can print a tidy price label without extra work. For 450 cents it prints $4.50; {:02} pads the cents to two digits.
Generics: one function, many types
Suppose we want a function that prints a label for any sellable thing. We do not want to write one for lattes and another for croissants. A generic function uses a placeholder type, usually called T.
fn print_label<T: Sellable>(item: &T) { println!("{}", item.label());}Read <T: Sellable> as “for any type T, as long as T is Sellable.” That : Sellable part is a trait bound. It tells the compiler what T is guaranteed to be able to do, so we may call .label() inside. Calling print_label(&Croissant) prints Croissant: $3.25.
The compiler checks the bound at compile time. If you try print_label(&42), you get an error like:
error[E0277]: the trait bound `{integer}: Sellable` is not satisfiedRead it as: “the number 42 never promised to be Sellable.” Fix it by passing something that did.
The impl Trait shorthand
For simple cases Rust has a shorter spelling that means the same thing:
fn print_label(item: &impl Sellable) { println!("{}", item.label());}Use impl Trait when it reads well, and <T: Trait> when you need to name T more than once.
Several bounds and where
Combine bounds with +. When the list grows, move it to a where clause:
fn cheaper_label<T>(a: &T, b: &T) -> Stringwhere T: Sellable,{ if a.price_cents() <= b.price_cents() { a.label() } else { b.label() }}Tip
Both parameters here are &T, so they must be the same type. That is a case where <T: Trait> is clearer than impl Trait.
Generic structs
Types can be generic too. You have already met Vec<T>, Option<T> and Result<T, E>; the T is the same idea. Here is a tiny tray that holds any kind of item:
struct Tray<T> { items: Vec<T>,}
impl<T: Sellable> Tray<T> { fn total_cents(&self) -> u32 { self.items.iter().map(|i| i.price_cents()).sum() }}impl<T: Sellable> means “these methods exist for trays of sellable things.” (The .iter().map(...) part is the topic of the next lesson.)
Derive: traits for free
Some traits are so common that Rust writes the code for you. You ask with #[derive(...)]:
#[derive(Debug, Clone, PartialEq)]struct Customer { name: String, loyalty_points: u32,}Debuglets you print the value with{:?}.Cloneadds.clone()to make a copy.PartialEqlets you compare two customers with==.
Warning
derive only works if every field also supports the trait. A struct containing a type without Debug cannot derive Debug; the error is error[E0277]: `NoDbg` doesn't implement `Debug` and points at the offending field.
Converting types: From and Into
You have been writing String::from("Latte") since the basics. That is the trait From at work: “build a String from this &str.” Whenever a type implements From<A>, Rust also gives you Into for free, which reads the other way round: “turn this A into that type.”
let a = String::from("Latte");let b: String = "Latte".into();Both lines make the same String. With .into() the compiler works out the target from the type you wrote on the left (: String), so the annotation is needed.
You can teach your own types to convert. Here a (name, price) pair becomes a MenuItem:
struct MenuItem { name: String, price_cents: u32,}
impl From<(&str, u32)> for MenuItem { fn from(pair: (&str, u32)) -> Self { MenuItem { name: pair.0.to_string(), price_cents: pair.1 } }}Now MenuItem::from(("Latte", 450)) and ("Latte", 450).into() both work.
Note
From is also how the ? operator converts errors: when a function returns Result<T, MyError>, ? calls MyError::from(...) on whatever error occurred. That is why error types in web code usually implement From.
Display: making println! friendly
{:?} (from Debug) is for programmers. When you want a customer-friendly message, you implement the trait std::fmt::Display, which is what {} uses. This answers the question from the structs lesson: “how do I print my own struct with {}?”
use std::fmt;
impl fmt::Display for MenuItem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} (${}.{:02})", self.name, self.price_cents / 100, self.price_cents % 100) }}fmtreceives a formatterf, a place to write text into.write!works likeprintln!but writes intof.- It returns
fmt::Result, soprintln!("{item}")can report a failure if one happens.
Once this exists, println!("{item}") prints Latte ($4.50). The {item} form puts a variable name straight inside the braces.
The whole café in one program
Here is everything from this lesson assembled into one complete program. Copy it into a fresh src/main.rs and run it.
use std::fmt;
trait Sellable { fn name(&self) -> String; fn price_cents(&self) -> u32;
fn label(&self) -> String { format!("{}: ${}.{:02}", self.name(), self.price_cents() / 100, self.price_cents() % 100) }}
#[derive(Debug, Clone, PartialEq)]struct MenuItem { name: String, price_cents: u32,}
impl From<(&str, u32)> for MenuItem { fn from(pair: (&str, u32)) -> Self { MenuItem { name: pair.0.to_string(), price_cents: pair.1 } }}
impl fmt::Display for MenuItem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} (${}.{:02})", self.name, self.price_cents / 100, self.price_cents % 100) }}
impl Sellable for MenuItem { fn name(&self) -> String { self.name.clone() } fn price_cents(&self) -> u32 { self.price_cents }}
struct Tray<T> { items: Vec<T>,}
impl<T: Sellable> Tray<T> { fn total_cents(&self) -> u32 { self.items.iter().map(|i| i.price_cents()).sum() }}
fn print_label<T: Sellable>(item: &T) { println!("{}", item.label());}
fn main() { let latte = MenuItem::from(("Latte", 450)); let croissant: MenuItem = ("Croissant", 325).into();
println!("{latte}"); println!("{:?}", croissant); print_label(&latte);
let tray = Tray { items: vec![latte.clone(), croissant] }; println!("Tray total: {} cents", tray.total_cents()); println!("Same item? {}", latte == latte.clone());}Latte ($4.50)MenuItem { name: "Croissant", price_cents: 325 }Latte: $4.50Tray total: 775 centsSame item? true- The
Sellabletrait promises a name and a price, with a defaultlabel. MenuItemderivesDebug,CloneandPartialEq, and getsFromandDisplayby hand.impl Sellable for MenuItemkeeps the promise.Tray<T>andprint_label<T>are generic, so they work withMenuItemand with any future sellable type.- In
main,.into()andFrombuild items,{latte}usesDisplay,{:?}usesDebug, and==usesPartialEq.
Why web code is full of traits
Web frameworks ask your types to keep promises: “can you be turned into JSON?”, “can you be sent as a response?”, “can you be put on a queue?”. You will see this in Laravel Rust: a job struct derives Queueable, and a mail struct derives Mailable. Those are derives that grant your struct a trait’s behaviour. Wrapper types such as Inject<T> (for services in queued jobs) and Sometimes<T> (for form fields that may be left out) are generics, exactly like our Tray<T>. After this lesson, Inject<T> should look friendly rather than scary.
Try it yourself
Both exercises build on the full listing above.
- Add a muffin (300 cents) to the tray, using
.into(), and print the new total. - Add a default method
fn is_cheap(&self) -> booltoSellablethat returnstruewhen the price is under 300 cents. Print whether a("Cookie", 200)item is cheap.
Show solution
- In
main, build the tray like this:
let muffin: MenuItem = ("Muffin", 300).into();let tray = Tray { items: vec![latte.clone(), croissant, muffin] };println!("Tray total: {} cents", tray.total_cents());It prints Tray total: 1075 cents (450 + 325 + 300).
- Add this inside
trait Sellable:
fn is_cheap(&self) -> bool { self.price_cents() < 300}Then let cookie: MenuItem = ("Cookie", 200).into(); println!("{}", cookie.is_cheap()); prints true. MenuItem needs no extra code, because default methods come for free.
Recap
- A trait is a promise of behaviour;
impl Trait for Typekeeps it, and traits can supply default methods. - Generics (
<T>) let one function or struct work with many types; a trait bound (T: Sellable) says whatTmust be able to do. #[derive(...)]generates common trait code for you.FromandIntoconvert between types ("Latte".into()), and?relies onFromfor errors.- Implement
Displayto makeprintln!("{item}")print your type nicely.
What’s next
Next we meet closures and iterators, the compact tools that turn a list of orders into totals and filtered menus: Closures and Iterators.
0 of 35 lessons complete