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

Generic Array Slices

Abstract operations over arrays of variable sizes using const generics.

In this lesson, you will learn how to write flexible functions that operate on arrays of any size using const generics and array slices.

The Problem with Fixed Sizes

In Rust, an array’s size is part of its type. A [i32; 3] is a fundamentally different type than a [i32; 4]. If you write a function that takes a fixed-size array as an argument, it becomes impossible to pass in an array of a different length. Previously, we might have resorted to using slices (&[i32]), but doing so discards the size information, meaning the compiler no longer knows exactly how many elements are in the container at compile time.

Introducing Const Generics for Slices

By combining const generics with array references, we can create functions that accept arrays of any size while preserving that size information in the function signature. This allows the compiler to enforce constraints on the data length while keeping our code reusable.

Consider a function that needs to ensure a buffer is always processed in a specific chunk size:

fn process_array<const N: usize>(data: &[i32; N]) {
    println!("Processing an array of {} elements.", N);
}

fn main() {
    let small = [1, 2];
    let large = [1, 2, 3, 4, 5];

    process_array(&small);
    process_array(&large);
}

Why This Matters

In this example, N acts as a placeholder for the length of the array. Because we defined data as &[i32; N], the compiler performs monomorphization—it generates a specialized version of process_array for every unique length you pass in.

This approach is a "zero-cost abstraction": it provides the safety and clarity of working with explicit array lengths, but at runtime, it behaves as if you had written a specific function for that exact array size. It avoids the overhead of dynamic bounds checking that often accompanies generic slice operations, and it keeps your logic clean by allowing you to use the constant N directly inside your algorithm (for example, when initializing a secondary buffer of the same size).

Key Takeaway: Const generics allow you to write reusable functions that accept arrays of any length while keeping the specific size known to the compiler at compile time.