Traits & Interface Contracts

🦀 Rust Lesson 12 Intermediate

Traits define abstract interface contracts in Rust. They describe shared behaviors that multiple different structures can implement.

1 Trait contracts and dynamic dispatch

Traits declare method signatures: `trait Summary { fn summarize(&self) -> String; }`. Classes implement traits using the `impl Trait for Struct` syntax. Traits support default implementations, and can be passed polymorphically using dynamic dispatch (`dyn Trait`).

2 Traits Code

Let's run a program implementing traits on custom structs:

Rust — Traits ▶ Run Code
trait Speak {
    fn speak(&self) -> String;
}

struct Dog;

// Implement Speak trait for Dog
impl Speak for Dog {
    fn speak(&self) -> String {
        String::from("Woof! Woof!")
    }
}

struct Cat;

impl Speak for Cat {
    fn speak(&self) -> String {
        String::from("Meow!")
    }
}

fn main() {
    let dog = Dog;
    let cat = Cat;

    println!("Dog: {}", dog.speak());
    println!("Cat: {}", cat.speak());
}
3 Code Challenge
Challenge: Create a trait called `Area` containing the method `fn area(&self) -> f64;`. Implement the trait on a `Circle` struct, and test your implementation in `main()`.