- 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
Generics
This lesson covers generics, which let you write one function that works with many types.
Generics use the <T> notation to declare a type variable whose actual type is decided later. The same logic can then be reused across different types.
The sample code defines fn largest<T: PartialOrd + Copy>(list: &[T]) -> T and finds the largest value in a slice of numbers. PartialOrd is the constraint (the trait bound) meaning "can be compared".
A common early stumble is specifying those trait bounds. Whatever you want to do with the generic type T — compare it, copy it — has to be stated explicitly as a constraint.
In professional work, much of the standard library, including Vec and Option, is implemented with generics.
๐งช 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).
