2.10 Traits
Traits define shared behavior (similar to interfaces in other languages). A trait declares method signatures, and types implement those methods.
2.10.1 Declaring a Trait
trait Drawable {
fn draw(&self);
}
2.10.2 Implementing a Trait
struct Circle;
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing a circle");
}
}
2.10.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.10.4 Comparison with C
C does not have a built-in concept of traits or interfaces. Often, function pointers or structs of function pointers (vtables) serve a similar purpose.