IT lexicon › Programming › Trait (Rust)

Trait (Rust)

Programming På svenska → Updated: 2026-05-26

Rust's mechanism for shared behavior. Similar to interfaces (Java) or typeclasses (Haskell). trait Animal { fn speak(&self) -> String; }. Implemented separately from the type.

Distinct from Java interface: you can implement a trait for types you don't own (orphan rule restricts cross-crate). Default implementations: a trait can provide method impls that can be overridden. Trait objects (dyn Trait) give runtime polymorphism (vtable-based). Static dispatch (generics + trait bounds) is the default — monomorphization. Major standard traits: Clone, Debug, Display, Iterator, Serialize/Deserialize. Async traits stabilized in Rust 1.75 (2023).

← Back to the lexicon