Traits, Rust's Interfaces
As the title says, traits are Rust’s alternative to Interfaces. They allow us to use polymorphism in Rust. We can create a trait like this:
1
2
3
trait Calculator {
fn add(&self, left: i32, right: i32) -> i32;
}
To implement the trait we use the impl keyword on a struct:
1
2
3
4
5
6
7
struct GoodCalculator {}
impl Calculator for GoodCalculator {
fn add(&self, left: i32, right: i32) -> i32 {
left + right
}
}

