liveBook · Manning

Const generics

As explained in Idiomatic Rust

A const generic is a Rust generic parameter whose value is a compile-time constant rather than a type.

Const generics let a type or struct parameterize a compile-time constant, such as an array’s length. They avoid creating a separate struct for every size and can keep fixed-size data in an array rather than a runtime-resizable Vec. section 7.1

#[derive(Debug)]
struct Buffer<T, const LENGTH: usize> {
    buf: [T; LENGTH],
}

The element type and constant length are separate parameters; LENGTH sets the array’s size. section 7.1

Use an integer-based primitive such as usize for the constant parameter; char and bool are also allowed, but floating-point values are not. A generic conversion implementation can accept arrays of different lengths while preserving each length in the Buffer type. section 7.1

impl<T, const LENGTH: usize> From<[T; LENGTH]> for Buffer<T, LENGTH> {
    fn from(buf: [T; LENGTH]) -> Self {
        Buffer { buf }
    }
}

This implementation converts an array into a Buffer with the same element type and length. section 7.1

Infer a buffer from an array

Converting [0, 1, 2, 3] with Buffer::from produces a Buffer containing those four values. section 7.1

How Idiomatic Rust covers it

How deep it goes
Defines the syntax, permitted parameter types, and generic array conversion, but does not detail compiler internals.
Examples
Demonstrates a generic Buffer, conversion from arrays, and debug output for a four-element buffer.
What you can do after
Build it from scratch by defining a Buffer with a const length parameter and implementing conversion from arrays.
How it connects
Connects const generics to Rust generics, arrays, structs, and Vec.

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 Idiomatic Rust. The section links point to the parts of the book it draws on.