Rust Tutorial: Generics
Write code that works for multiple types with generic functions, structs, and enums.
Write once, use for any type
Generics let you write code that works for multiple types while keeping full type safety.
Rust generics have zero runtime cost — the compiler generates concrete versions at compile time (monomorphisation).
What you'll learn in this Rust generics tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Generic function — A function with `<T>` works for any type.
- Bounded generics — Add trait bounds to restrict which types are accepted:
- Generic struct — Structs can be generic over one or more types.
- Multiple type parameters — Use multiple type parameters: `<T, U>`
- Generic enum — Option<T> and Result<T,E> are generic enums from the standard library. Write your own.
- Zero-cost abstraction — Generic code compiles to the same machine code as hand-written type-specific code.
- impl Trait in function position — `impl Trait` as a parameter type is shorthand for a generic bound.
- Phantom types — Sometimes you want a type parameter for type safety without storing the value.
Rust Generics concepts covered
- Write once, use for any type