Rust
Implementing a trait
Implement a trait with impl Trait for Type.
Implementing traits
The same trait can be implemented for many types; each defines the behaviour its own way:
trait Alan {
fn alan(&self) -> f64;
}
struct Kare { a: f64 }
struct Daire { r: f64 }
impl Alan for Kare {
fn alan(&self) -> f64 { self.a * self.a }
}
impl Alan for Daire {
fn alan(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
}
Standard library traits can be implemented for your own types too: impl std::fmt::Display for Kare.
Implementing Display
To print with {}, std::fmt::Display is implemented. Its only method is fmt, which writes to the formatter with write!:
use std::fmt;
impl fmt::Display for Kare {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Kare({})", self.a)
}
}
println!("{}", Kare { a: 3.0 }); // Kare(3)
Every type implementing Display also gets the to_string() method for free.
Exercise Two shapes
Define trait Alan and implement it for the types Kare { a: f64 } and Daire { r: f64 }. Print the areas of Kare { a: 3.0 } and Daire { r: 2.0 } with {:.2}, separated by a space.
Show example solution
trait Alan {
fn alan(&self) -> f64;
}
struct Kare {
a: f64,
}
struct Daire {
r: f64,
}
impl Alan for Kare {
fn alan(&self) -> f64 {
self.a * self.a
}
}
impl Alan for Daire {
fn alan(&self) -> f64 {
std::f64::consts::PI * self.r * self.r
}
}
fn main() {
println!("{:.2} {:.2}", Kare { a: 3.0 }.alan(), Daire { r: 2.0 }.alan());
}
Test yourself
-
What does the orphan rule forbid?
- Implementing your own trait for String
- Implementing Display
- Implementations where both the trait and the type come from other crates
- Implementing two traits for one type
Show answer
Implementations where both the trait and the type come from other crates — You can't write impl Display for Vec<i32>; both come from std. At least one of the trait or the type must be in your crate.
-
Write to the formatter
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
____(f, "Kare({})", self.a)
}
Show answer
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Kare({})", self.a)
}
-
Implementation and permission
- impl Alan for Kare
- Allowed (both yours)
- impl Display for Kare
- Allowed (type is yours)
- impl Alan for String
- Allowed (trait is yours)
- impl Display for Vec<i32>
- Forbidden (orphan rule)
Next lesson: Default methods