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?

  1. 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());
    }
    
    What does this program print?
  2. 2Read

    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.

  3. 3Code

    A trait and a trait bound

    1 / 2
    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);
    }
    

    Read the program. What will it print?

    Run it in the playground

  4. 4Read

    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.

  5. 5Code

    Display, derive and trait objects

    1 / 2
    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());
        }
    }
    

    Read the program. What will it print?

    Run it in the playground

  6. 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 });
    }
    
    This program does not compile. What is the bug?
  7. 7Say it back

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

  1. AgentRouter Free Credits

    Free AI coding credits: $25 per daily check-in and $50 per invite

    No cardVerified

  2. Cursor Free Plan

    Cursor Agent with limited agent and chat requests, $0/month

    No cardVerified

  3. Cline Free Models

    Try select models free in Cline via rotating promotions with a usage quota

    No cardVerified

All free ai coding tools →

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

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

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer