Course contentsShow
← Rust
Lesson 681 of 1,9106. Generics and Static DispatchFree lesson

Const Generics Fundamentals

Implement fixed-size arrays and logic that depends on integer values known at compile time.

In this lesson, you will learn how to parameterize types with constant values, enabling you to build structures that encode their size directly into their type definition.

Beyond Type Parameters

Up until now, you have used generic type parameters (like <T>) to make your structs work with any data type. However, sometimes you need your logic to change based on a value known at compile time rather than just a type. This is where Const Generics come in.

Const generics allow you to use values—specifically integers, booleans, or characters—as generic parameters. The most common use case is defining a fixed-size array where the length is part of the type.

Defining Const Generics

To define a const generic, you use square brackets [] inside the angle brackets. Here is a simple Buffer struct that can hold a specific number of items:

struct Buffer<T, const N: usize> {
    data: [T; N],
}

fn main() {
    // We create a buffer of 3 integers
    let b1 = Buffer { data: [1, 2, 3] };
    
    // We create a buffer of 5 integers
    let b2 = Buffer { data: [10, 20, 30, 40, 50] };
}

In this example, N is a constant known at compile time. Because N is part of the type, Buffer<i32, 3> and Buffer<i32, 5> are considered completely different types by the Rust compiler.

Why This Matters

This approach allows you to write functions that work only on specific array sizes while keeping the code reusable. Because these sizes are known at compile time, the compiler can generate highly optimized code for each specific size (monomorphization), ensuring that you don't pay a runtime penalty for this flexibility.

You can also perform logic based on these constants. For example, if you wanted to implement a new method, you could ensure the internal array is initialized based exactly on the provided constant N. This brings a new level of safety to your data structures, as the compiler will prevent you from accidentally passing an array of the wrong size to a function expecting a specific buffer length.

Key Takeaway: Const generics allow you to include fixed values—like array lengths—in your type definitions, enabling compile-time type safety and high-performance, specialized code for specific data sizes.