🦀 Rust Beginner

What are traits in Rust?

Answer

Traits in Rust are similar to interfaces in other languages — they define a set of methods that a type must implement to "be" that trait. Define a trait with trait Drawable { fn draw(&self); } and implement it for a type with impl Drawable for Circle { fn draw(&self) { ... } }. Traits enable polymorphism: a function can accept any type that implements a trait using generics (fn render<T: Drawable>(item: T)) or trait objects (fn render(item: &dyn Drawable)). The standard library's most important traits include Display, Debug, Clone, Copy, Iterator, From/Into, and PartialEq. Unlike interfaces, traits can have default method implementations.