Implementing a trait
- Rust course
- Intermediate
- Lesson 2/115
- 4 min
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.
Practice 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.
Starter code
fn main() {
// buraya yaz
}Sample 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());
}Expected output
9.00 12.57
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- Implementing two traits for one type
Explanation: 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.
2 Write to the formatter
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
____(f, "Kare({})", self.a)
}
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Kare({})", self.a)
}
Explanation: write! writes formatted text to the given target and returns fmt::Result.
3 Implementation and permission
| Term | Meaning |
|---|---|
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) |