Traits in Rust: shared behaviour
Learn Rust · Beginner · 12 min · After Option, Result and the ? operator in Rust
How do different types share the same behaviour?
1Guess
trait Describe { fn name(&self) -> String; fn describe(&self) -> String { format!("This is {}", self.name()) } } struct Cat; struct Robot; impl Describe for Cat { fn name(&self) -> String { String::from("a cat") } } impl Describe for Robot { fn name(&self) -> String { String::from("a robot") } fn describe(&self) -> String { String::from("Beep. I am a robot") } } fn main() { println!("{}", Cat.describe()); println!("{}", Robot.describe()); }2Read
Traits
A trait is a set of method signatures that a type can promise to provide. You write
impl Trait for Typeand fill in the methods. A trait can give a method a default body, and a type may keep it or override it. A default method can call the other methods of the same trait, likedescribecallsname.3Code
A trait and a trait bound
1 / 2trait Area { fn area(&self) -> u32; } struct Rect { w: u32, h: u32, } struct Square { side: u32, } impl Area for Rect { fn area(&self) -> u32 { self.w * self.h } } impl Area for Square { fn area(&self) -> u32 { self.side * self.side } } fn print_area<T: Area>(shape: &T) { println!("area {}", shape.area()); } fn print_twice(shape: &impl Area) { println!("twice {}", shape.area() * 2); } fn main() { let rect = Rect { w: 3, h: 4 }; let square = Square { side: 5 }; print_area(&rect); print_area(&square); print_twice(&rect); }Read the program. What will it print?
4Read
Derive, Display and dyn
Many traits can be written for you:
#[derive(Debug, Clone, PartialEq)]adds debug printing, cloning and==.Displayhas no derive, so you implementfmt::Displayby hand to use{}. To mix types in oneVec, use a trait object:Vec<Box<dyn Area>>picks the method at run time.5Code
Display, derive and trait objects
1 / 2use std::fmt; trait Area { fn area(&self) -> u32; } struct Rect { w: u32, h: u32, } struct Square { side: u32, } impl Area for Rect { fn area(&self) -> u32 { self.w * self.h } } impl Area for Square { fn area(&self) -> u32 { self.side * self.side } } #[derive(Debug, PartialEq)] struct Point { x: i32, y: i32, } impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn main() { let p = Point { x: 1, y: 2 }; println!("{p}"); println!("{p:?}"); println!("{}", p == Point { x: 1, y: 2 }); let shapes: Vec<Box<dyn Area>> = vec![Box::new(Rect { w: 2, h: 3 }), Box::new(Square { side: 4 })]; for shape in &shapes { println!("area {}", shape.area()); } }Read the program. What will it print?
6Fix
trait Area { fn area(&self) -> u32; } struct Rect { w: u32, h: u32, } struct Square { side: u32, } impl Area for Rect { fn area(&self) -> u32 { self.w * self.h } } fn print_area<T: Area>(shape: &T) { println!("area {}", shape.area()); } fn main() { print_area(&Rect { w: 3, h: 4 }); print_area(&Square { side: 5 }); }7Say it back
8Mission · 10 min
Define a trait Speak with a method that returns a String. Implement it for two animal structs, put one of each in a Vec<Box<dyn Speak>> and print what each says.
cargo new animals cd animals cargo run
Free AI coding tools to practise with
- AgentRouter Free Credits
Free AI coding credits: $25 per daily check-in and $50 per invite
No cardVerified
- Cline Free Models
Try select models free in Cline via rotating promotions with a usage quota
No cardVerified
Common questions
- What is a trait in Rust?
- A trait is a set of methods that a type can implement. It describes behaviour without saying what the data looks like. You declare it with the trait keyword and give a type the behaviour with impl Trait for Type. Traits are similar to interfaces in other languages, and they can also carry default method bodies.
- What is a trait bound in Rust?
- A trait bound limits a generic type to types that implement a trait, for example fn print_area<T: Area>(shape: &T). Inside the function you can call the trait methods on the value. Calling it with a type that lacks the impl is a compile error. impl Area in the parameter position is shorthand for the same thing.
- When do I need dyn Trait instead of a generic?
- A generic function is built for one concrete type at each call. When one collection must hold different types, such as a Vec of shapes, use a trait object: Vec<Box<dyn Area>>. The method is then chosen at run time. Generics avoid that cost, while trait objects let you mix types in one place.
Sources
- https://doc.rust-lang.org/book/ch10-02-traits.html (read 2026-12-03)
- https://doc.rust-lang.org/book/ch18-02-trait-objects.html (read 2026-12-03)
- https://doc.rust-lang.org/std/fmt/trait.Display.html (read 2026-12-03)
Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03
Published Dec 3, 2026 · Updated Dec 3, 2026