impl blocks attach inherent methods and trait implementations to types. Use Self inside impl; associated functions (no self) act like static methods.
Inherent vs trait impl
impl Rectangle {
fn area(&self) -> u32 { self.w * self.h }
}
Self-check
- What is an associated function?
- Can you add impl blocks for types you do not own with traits you define?
Trait impl blocks
impl Display for Rectangle implements a trait for a type. Orphan rules: you need either the trait or the type in your crate to add impls—prevents incoherent implementations.
Associated types and constants also live in impl blocks on traits (covered later in the track).