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

Const Generics with Arrays

Write generic linear algebra routines that work specifically on fixed-dimension vectors.

In this lesson, you will learn how to use const generics to write linear algebra functions that adapt to any vector size while maintaining type safety.

The Problem: Hard-coded Dimensions

Previously, if you wanted to write a function to add two vectors together, you might have been forced to write separate functions for 2D vectors and 3D vectors. This leads to code duplication. With const generics, we can treat the size of an array as a parameter, allowing one function to handle vectors of any fixed length.

Implementing a Generic Vector Adder

When we define a function with a const generic parameter N, Rust treats N as a compile-time constant. This allows us to accept arrays of type [f64; N].

fn add_vectors<const N: usize>(a: [f64; N], b: [f64; N]) -> [f64; N] {
    let mut result = [0.0; N];
    for i in 0..N {
        result[i] = a[i] + b[i];
    }
    result
}

fn main() {
    let v1 = [1.0, 2.0, 3.0];
    let v2 = [4.0, 5.0, 6.0];
    
    // The compiler knows these are [f64; 3]
    let sum = add_vectors(v1, v2);
    println!("{:?}", sum);
}

Why This Matters

In linear algebra, the dimension of a vector is critical. If you tried to add a 2-element array to a 3-element array, the compiler would see [f64; 2] and [f64; 3] as two completely different types. Because our function requires both inputs to be [f64; N], the code will fail to compile if the dimensions don't match.

This gives us the best of both worlds: the performance of stack-allocated arrays and the flexibility of generic programming, all while preventing dimension-mismatch bugs at compile time. You no longer need to write manual checks or use dynamic allocation to handle different vector sizes; the compiler enforces the math for you.

Key Takeaway: Const generics allow you to write functions that operate on arrays of any size N, ensuring that dimension-specific logic is both reusable and type-safe at compile time.