Generic Structs and Enums
Build flexible data types.
Generic Data Structures
Just like functions, structs and enums can be generic over one or more types. This lets a single definition hold values of any type.
The standard library is built this way: Vec<T>, Option<T>, and Result<T, E> are all generic.
A Generic Struct
Declare the type parameter after the struct name, then use it for fields. Here Point stores two values of the same type T.
One definition now serves integer points, float points, and more.
struct Point<T> {
x: T,
y: T,
}All lessons in this course
- Generic Functions
- Generic Structs and Enums
- Trait Bounds
- where Clauses and Multiple Bounds