0PricingLogin
Learn Rust Coding · Lesson

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

  1. Generic Functions
  2. Generic Structs and Enums
  3. Trait Bounds
  4. where Clauses and Multiple Bounds
← Back to Learn Rust Coding