---
title: "Traits in Rust: shared behaviour"
slug: "traits"
description: "Share behaviour between types with traits: default methods, trait bounds, derive, Display and Box<dyn Trait>. Fix a type that is missing its impl."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-rust/traits"
---

# Traits in Rust: shared behaviour

How do different types share the same behaviour?

## Predict

```rust
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());
}
```

What does this program print?

- This is a cat, then This is a robot
- It does not compile because Cat has no describe
- This is a cat, then Beep. I am a robot

Answer: This is a cat, then Beep. I am a robot — Cat uses the default, which calls name. Robot overrides describe.

Output:

```
This is a cat
Beep. I am a robot
```

A type gets the default method unless it writes its own. `Cat` uses the default, and `Robot` overrides it.

## Traits

A **trait** is a set of method signatures that a type can promise to provide. You write `impl Trait for Type` and 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, like `describe` calls `name`.

## A trait and a trait bound

```rust
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
    }
}

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);
}
```

Output:

```
area 12
area 25
twice 24
```

`T: Area` is a **trait bound**: `print_area` accepts any type that implements `Area`. `&impl Area` is shorthand for the same idea. The compiler builds a version of the function for each type.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=136dbdb7ca9d98715fe1aa29c67e35dd

## Derive, Display and dyn

Many traits can be written for you: `#[derive(Debug, Clone, PartialEq)]` adds debug printing, cloning and `==`. `Display` has no derive, so you implement `fmt::Display` by hand to use `{}`. To mix types in one `Vec`, use a **trait object**: `Vec<Box<dyn Area>>` picks the method at run time.

## Display, derive and trait objects

```rust
use 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());
    }
}
```

Output:

```
(1, 2)
Point { x: 1, y: 2 }
true
area 6
area 16
```

`Display` gives `{p}` and `Debug` gives `{p:?}`. `PartialEq` makes `==` work on `Point`. The `Vec` holds a `Rect` and a `Square` because both sit behind `Box<dyn Area>`.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=3ed2c50c33334d54da9bef05e11173e2

## Fix it

```rust
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 });
}
```

This program does not compile. What is the bug?

- print_area needs &mut instead of &
- Square does not implement Area, so it fails the bound T: Area
- Rect must be defined after Square

Answer: Square does not implement Area, so it fails the bound T: Area — Add impl Area for Square and the call compiles.

Compiler message:

```
error[E0277]: the trait bound `Square: Area` is not satisfied
```

Fixed:

```rust
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
    }
}

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 });
}
```

Output:

```
area 12
area 25
```

## Say it back

In your own words: what does the trait bound T: Area mean?

Our sentence: The function accepts only types that implement Area. Inside it can call area() on the value, and the compiler rejects any other type.

## Mission (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.

```sh
cargo new animals
cd animals
cargo run
```

## 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.
