liveBook · Manning

Const generics

As explained in Learn Rust in a Month of Lunches

Const generics are Rust generics that parameterize types or implementations with compile-time constant values.

Const generics let Rust items accept compile-time constant values as generic parameters. Alongside type and lifetime generics, they form Rust’s third kind of generic parameter. They are especially useful for arrays, whose types include both an element type and a length. section 16.1 section 16.6

Const generics solve a common array-size problem:

  • An [i32; 3] and an [i32; 4] are different types because their lengths differ. section 16.1
  • Without const generics, separate structs and trait implementations may be needed for every supported array length. section 16.1
  • With const N: usize, one definition can use [T; N] for many element types and array lengths. section 16.1

A buffer whose size is part of its type

struct Buffers<T, const N: usize> { array_one: [T; N], array_two: [T; N], } This single definition can create a three-element u8 buffer or a four-element i32 buffer. The compiler uses the supplied type and constant length to determine each concrete type. section 16.1

struct Buffers<T, const N: usize> {
    array_one: [T; N],
    array_two: [T; N]
}

Inspect the compact generic buffer definition using both a type parameter and a const length parameter. section 16.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines const parameters and works through array buffers, but stops short of compiler internals or advanced constraints.
Examples
Demonstrates fixed-size byte buffers, reusable Buffers<T, const N> structs, and concrete arrays with different types and lengths.
What it assumes
Assumes familiarity with type generics and lifetimes while introducing const parameters through array examples.
What you can do after
Build reusable array-backed structs whose element types and lengths are selected at compile time.
How it connects
Connects const generics with type generics, lifetimes, arrays, structs, and trait implementations.

Also explained in

Compare how 2 books explain const generics →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.