Types and contracts
What are traits?
On this page
Traits describe sets of behaviours that types can implement. In Rust a trait can require methods and provide default implementations. A generic function bounded by a trait can use the promised behaviours for each suitable type. A trait object enables runtime dispatch when the trait supports it.
Worked example
Rusttrait Versioned {
fn version(&self) -> u32;
fn is_current(&self, expected: u32) -> bool {
self.version() == expected
}
}
struct Revision(u32);
impl Versioned for Revision {
fn version(&self) -> u32 { self.0 }
}
fn main() {
assert!(Revision(7).is_current(7));
}Explore class relationships in the OOP Playground