Browse OOP reference
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

Rust
trait 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));
}

The Rust Programming Language on traits

Explore class relationships in the OOP Playground

How do modern languages approach object orientation?What is a method?What is the object-relational impedance mismatch?

All OOP questions

Search ObjectFAQ