๐งฌ Traits in Rust
Traits are like interfaces in other languages. They define shared behavior that types can implement.
๐ฆ Define a Trait
๐งฑ Implement a Trait
๐งช Use the Trait
๐งโ๐คโ๐ง Trait for Multiple Types
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)
Or using shorthand syntax:
๐งต Multiple Traits
๐ Derive Common Traits
Rust has built-in traits that you can automatically derive:
๐ฆ 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 |