Skip to content

๐Ÿงฌ Traits in Rust

Traits are like interfaces in other languages. They define shared behavior that types can implement.


๐Ÿ“ฆ Define a Trait

trait Speak {
    fn speak(&self);
}

๐Ÿงฑ Implement a Trait

struct Dog;

impl Speak for Dog {
    fn speak(&self) {
        println!("Woof!");
    }
}

๐Ÿงช Use the Trait

let d = Dog;
d.speak(); // Woof!

๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ Trait for Multiple Types

struct Cat;

impl Speak for Cat {
    fn speak(&self) {
        println!("Meow!");
    }
}

Now both Dog and Cat implement Speak.


โœจ Default Methods

Traits can have default method implementations:

trait Greet {
    fn greet(&self) {
        println!("Hello!");
    }
}

struct Person;

impl Greet for Person {} // uses default

๐Ÿ“ฆ Traits with Parameters

trait Addable {
    fn add(self, other: Self) -> Self;
}

impl Addable for i32 {
    fn add(self, other: Self) -> Self {
        self + other
    }
}

๐Ÿงฎ Trait Bounds (Generics)

fn print_speak<T: Speak>(item: T) {
    item.speak();
}

Or using shorthand syntax:

fn print_speak(item: impl Speak) {
    item.speak();
}

๐Ÿงต Multiple Traits

fn do_stuff<T: Trait1 + Trait2>(x: T) {
    // ...
}

๐Ÿ”Œ Derive Common Traits

Rust has built-in traits that you can automatically derive:

#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

๐Ÿ“ฆ Common Built-in Traits

Trait Purpose
Debug {:?} formatting
Clone Deep copy
Copy Shallow copy (for simple types)
PartialEq == and !=
Eq Total equality
PartialOrd <, >, etc. (partial comparison)
Ord Total ordering
Default ::default()
Drop Custom destructor
From / Into Type conversions