Rust Notes — Module 4

Rust Notes — Module 4: Traits 1. What is a Trait? A trait defines a set of behaviors (methods) that a type must implement. It is a contract — any type that implements the trait promises to provide those behaviors. trait Greet { fn hello(&self) -> String; } Concept Rust C++ Go Trait trait abstract class / concept interface Implementation impl Trait for Type override virtual method implicit (duck typing) Dispatch static (default) or dynamic virtual table interface table 2. Implementing a Trait struct Human { name: String } struct Robot { id: u32 } impl Greet for Human { fn hello(&self) -> String { format!("Hi, I'm {}!", self.name) } } impl Greet for Robot { fn hello(&self) -> String { format!("BEEP. I AM UNIT {}.", self.id) } } Each type provides its own implementation of the trait methods. A type can implement any number of traits. You can implement traits for types you didn’t define (with some restrictions — see orphan rule below). 3. Default Implementations Traits can provide default method implementations. Types can override them or inherit them for free: ...

March 21, 2026 · 8 min