Skip to main content Traits | Rust Fundamentals lesson | BraveProgrammerTraits
Traits define shared behavior across types, similar to interfaces in other languages. They enable polymorphism and code reuse in Rust.
Defining Traits
trait Drawable {
fn draw(&self);
}
trait Area {
fn (&) ;
}
area
self
->
f64
Trait methods have signatures but no implementations (in the trait definition).
Implementing Traits
struct Circle {
radius: f64,
}
impl Drawable for Circle {
fn draw(&self) {
println!(\"Drawing circle with radius {}\", self.radius);
}
}
impl Area for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
fn main() {
let circle = Circle { radius: 5.0 };
circle.draw();
println!(\"Area: {}\", circle.area());
}
Default Implementations
Traits can provide default behavior:
trait Sound {
fn make_sound(&self) {
println!(\"Generic sound\");
}
}
struct Dog;
impl Sound for Dog {
fn make_sound(&self) {
println!(\"Woof!\"); // Override
}
}
struct Rock;
impl Sound for Rock {} // Use default
fn main() {
Dog.make_sound(); // Woof!
Rock.make_sound(); // Generic sound
}
Trait Objects
Use traits for dynamic dispatch:
trait Animal {
fn speak(&self);
}
struct Dog;
impl Animal for Dog {
fn speak(&self) { println!(\"Woof!\"); }
}
struct Cat;
impl Animal for Cat {
fn speak(&self) { println!(\"Meow!\"); }
}
fn main() {
let animals: Vec<Box<dyn Animal>> = vec![
Box::new(Dog),
Box::new(Cat),
];
for animal in animals {
animal.speak();
}
}
The dyn keyword indicates dynamic dispatch (slower but flexible).
Trait Bounds
Generic functions can require types to implement traits:
fn print_it<T: std::fmt::Display>(val: T) {
println!(\"Value: {}\", val);
}
fn main() {
print_it(42);
print_it(\"hello\");
// print_it(vec![1,2]); // ERROR: Vec doesn't implement Display
}
Multiple Trait Bounds
fn print_and_compare<T: std::fmt::Display + PartialOrd>(a: T, b: T) {
if a > b {
println!(\"a is greater: {}\", a);
} else {
println!(\"b is greater: {}\", b);
}
}
Trait Bounds with Where Clause
For complex bounds, use where:
fn compare<T, U>(a: T, b: U) -> bool
where
T: std::fmt::Display + PartialOrd<U>,
U: std::fmt::Display,
{
a > b
}
Implementing Standard Traits
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl PartialOrd for Point {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
let self_dist = self.x * self.x + self.y * self.y;
let other_dist = other.x * other.x + other.y * other.y;
self_dist.partial_cmp(&other_dist)
}
}
Common Traits
- Clone: Duplicate values
- Copy: Implicit copying
- Debug: Debug formatting
- Display: User-friendly formatting
- PartialEq, Eq: Equality
- PartialOrd, Ord: Ordering
- From, Into: Type conversion
- Iterator: Iteration support
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities