Trait (Rust)

A trait defines a set of methods that a type can implement — Rust's version of an interface. Traits enable shared behavior and are the foundation of Rust's generics and polymorphism.

Rust

A trait is a contract: it declares method signatures (and optional default implementations). Any type that implements the trait with impl Trait for Type can be used wherever that behavior is required. Common standard traits include Display, Debug, Clone, Iterator, and PartialOrd.

Traits drive polymorphism two ways: static dispatch via generics with trait bounds (fn f<T: Display>(x: T)), resolved at compile time with no runtime cost, and dynamic dispatch via trait objects (Box<dyn Trait>), resolved at runtime.

Because of the orphan rule you can implement a trait for a type only if you own the trait or the type. Default methods let a trait provide behavior automatically, so implementors override only what they need.

Syntax

trait Greet { fn hello(&self) -> String; }
impl Greet for Dog { fn hello(&self) -> String { "woof".into() } }

Examples

Rust

trait Area { fn area(&self) -> f64; }
struct Square(f64);
impl Area for Square {
    fn area(&self) -> f64 { self.0 * self.0 }
}

fn main() {
    println!("{}", Square(3.0).area());
}

Output:

9

Learn it in a lesson

See also

Back to the Dictionary