2.9 Traits and Implementations

2.9.1 Traits

Traits in Rust are similar to interfaces in other languages, defining shared behavior.

trait Drawable {
    fn draw(&self);
}

2.9.2 Implementing Traits

struct Circle;

impl Drawable for Circle {
    fn draw(&self) {
        println!("Drawing a circle");
    }
}

2.9.3 Using Traits

trait Drawable {
    fn draw(&self);
}

struct Circle;

impl Drawable for Circle {
    fn draw(&self) {
        println!("Drawing a circle");
    }
}

fn main() {
    let c = Circle;
    c.draw();
}

2.9.4 Comparison with C

C does not have traits or interfaces built into the language. Similar behavior is often achieved using function pointers or structs of function pointers (vtable pattern).