capypad
0 day streak
rust / beginner
Snippet

Trait Basics and Implementation

Traits define shared behavior that multiple types can implement. They are similar to interfaces in other languages. The dyn keyword creates a trait object for dynamic dispatch. Traits enable polymorphism and code reuse across different types.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
trait Summable {
fn sum(&self) -> i32;
}
 
struct Point {
x: i32,
y: i32,
}
 
impl Summable for Point {
fn sum(&self) -> i32 {
self.x + self.y
}
}
 
fn total(items: &[&dyn Summable]) -> i32 {
items.iter().map(|p| p.sum()).sum()
}
 
fn main() {
let p1 = Point { x: 3, y: 4 };
let p2 = Point { x: 5, y: 6 };
println!("Total: {}", total(&[&p1, &p2]));
}
Breakdown
1
trait Summable { ... }
Defines a trait with one required method signature
2
impl Summable for Point { ... }
Implements the trait for the Point struct
3
&[&dyn Summable]
Reference to slice of trait objects for dynamic dispatch