- 01Setting up (what you'll need)
- 02Your first output (println!)
- 03Variables and mutability (let / mut)
- 04Type annotations and basic types
- 05Branching (the if statement)
- 06Repeating (the for loop)
- 07Writing your own function
- 08Repeating (while and loop)
- 09Ownership, the basics
- 10Borrowing (references, &)
- 11Working with vectors (Vec)
- 12Structs
- 13enum and the match expression
- 14The Option type (null safety)
- 15The Result type and error handling
- 16Traits
- 17Generics
- 18Closures
- 19Working with strings (String)
- 20[Project] Build a small inventory system
Traits
This lesson covers the trait, which gives several types a shared behaviour.
A trait is close to an interface in other languages: it defines the promise that "this type has these methods". You supply the implementation for a concrete type by writing impl TraitName for TypeName.
The sample code defines trait Speak { fn speak(&self) -> String; } and implements it for a Dog struct with impl Speak for Dog.
A common early stumble is that the trait's declaration (what a type should be able to do) is separate from its implementation (how it actually works). That separation is also what lets you add new behaviour to an existing type after the fact.
In professional work, traits are used widely wherever several types need a shared interface — "can be displayed", "can be compared", and so on.
๐งช This site can't compile or run Rust directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ nothing is sent anywhere).
