skip to content

In Rust, how do you write one function that takes `[i32; 3]` and `[i32; 5]` arrays by value, and what does its `N` stand for?

level: juniorimportance: should knowfreq 40%

answer

  1. length is part of the array type
  2. a value, not a type, as parameter
  3. const N: usize
  4. inferred from the argument

basics

~20 s

Declare a const generic parameter: fn sum<const N: usize>(values: [i32; N]). N is a usize value fixed at compile time, inferred from the argument's array type, and rustc compiles one copy of sum for each length the program uses.

solid answer

~40 s

In Rust the length is part of an array's type, so `[i32; 3]` and `[i32; 5]` are different types. A **const generic parameter** abstracts over that value: `fn sum<const N: usize>(values: [i32; N]) -> i32`. At each call rustc infers `N` from the argument (`sum([1, 2, 3])` gives `N = 3`), or you can spell it with a turbofish, `sum::<4>(...)`. `N` is a compile-time constant usable in the body like any `const`, and each distinct length gets its own monomorphized copy. Const generics have been stable since Rust 1.51, and std uses them so that most array trait impls cover every length.

code

rust · 17 lines
rust
fn sum<const N: usize>(values: [i32; N]) -> i32 {
    let mut total = 0;
    for v in values {
        total += v;
    }
    println!("N = {N}");
    total
}

fn main() {
    let three = [1, 2, 3];
    let five = [10; 5];
    println!("{}", sum(three));
    println!("{}", sum(five));
    println!("{}", sum::<4>([1, 1, 1, 1]));
    println!("{:?}", three); // arrays of Copy elements are Copy
}

go deeper

for a junior

Recall that an array's length is part of its type and that const N: usize lets one function accept every length, with N inferred at the call.

for a middle

Explain that N is a compile-time constant, that each length is monomorphized separately, and when a slice parameter is the better choice.

for a senior

Know the edges: E0435 for run-time values, braces around computed const arguments, and Default for arrays still stopping at length 32.

for a principal

Weigh per-length code copies against a single slice-based function when an API takes arrays on a hot path or in a size-sensitive binary.

## Why array length needs its own kind of parameter In Rust a fixed-size array has the type `[T; N]`, and the **length `N` is part of the type**. `[i32; 3]` and `[i32; 5]` are as different to the type checker as `i32` and `String`. A function written for `[i32; 3]` will not accept `[i32; 5]`, and the type mismatch is reported as **E0308**. Ordinary generics (`fn f<T>(x: T)`) abstract over *types*. To abstract over the *value* in the length position, Rust has **const generic parameters**, declared with the `const` keyword and a type: ```rust fn sum<const N: usize>(values: [i32; N]) -> i32 { let mut total = 0; for v in values { total += v; } total } ``` Here `N` is not a variable that exists at run time. It is a **compile-time constant**, and inside the function it can be used anywhere a `const` item could be used: in an expression (`println!("{N}")`), in a local type (`let buf: [u8; N];`), or as the length of another array. ## How a call picks N - **Inference**: `sum([1, 2, 3])` passes a `[i32; 3]`, so rustc infers `N = 3`. `sum([10; 5])` infers `N = 5`. Most calls never name `N`. - **Turbofish**: `sum::<4>([1, 1, 1, 1])` states it explicitly. A literal or a named `const` can go there directly; a computed expression must be wrapped in braces, such as `sum::<{ 2 + 2 }>(...)`. - **Must be known at compile time**: a value read at run time cannot become `N`. Writing `Matrix::<n, n>` with a `let n` produces **E0435**, "attempt to use a non-constant value in a constant". Passing a `Vec<i32>` does not work either: a `Vec` is not an array type, and rustc reports E0308 with "expected `[i32; _]`, found `Vec<{integer}>`". ## What it costs Const generics are monomorphized exactly like type generics: the compiler generates one copy of `sum` for `N = 3`, another for `N = 5`, and so on. Each copy knows its length as a constant, which lets the optimizer unroll loops and drop bounds checks. The price is one copy of machine code per distinct length, which is the usual generics trade-off covered with bounds and monomorphization. | Parameter style | What varies | Copies of the function | Length known | |---|---|---|---| | `values: [i32; N]` with `const N: usize` | the array length | one per length used | at compile time | | `values: &[i32]` | nothing, one slice type | one | at run time, from the slice | | `values: [i32; 3]` | nothing | one | fixed at 3 | A slice parameter (`&[i32]`) is the alternative when the length is only known at run time or when one shared copy matters more than per-length optimisation; slices themselves are covered in the material on borrowed views. ## Arrays of any length in std Before const generics stabilised in **Rust 1.51**, std could only implement traits for arrays through macros, one length at a time, and most array impls stopped at 32 elements. Rust 1.47 already moved std's trait impls to every length internally, and 1.51 opened the same ability to user code. Today `Debug`, `PartialEq`, `Clone`, `IntoIterator` and the other array impls work for every length, with one notable exception: 1. `impl<T: Default> Default for [T; N]` is still written out by a macro for lengths 0 to 32 in `core`. 2. So `let a: [u8; 32] = Default::default();` compiles, while `[u8; 33]` fails with **E0277**, "the trait bound `[u8; 33]: Default` is not satisfied". 3. The reason, as a comment in `core` explains, is that `[T; 0]` implements `Default` without requiring `T: Default`, and separate impl blocks for different lengths are not supported for const generics yet. ## Common misreadings - `N` is not a hidden run-time argument; nothing is passed for it. - The turbofish is optional whenever the argument type already fixes the length. - `N` can be any allowed const type, not only `usize`, but array lengths are always `usize`. - Generic code over arrays no longer needs a macro per length; that was the situation before 1.51.

  • When would you take `&[i32]` instead of `[i32; N]`?
    When the length is only known at run time, when callers hold a `Vec` or part of an array, or when one shared copy of the code matters more than per-length optimisation. A slice carries its length at run time; `[i32; N]` bakes it into the type and generates a copy per length.
  • Can `N` come from a value the program reads at start-up?
    No. A const argument must be a compile-time constant: a literal, a `const` item, a braced constant expression or an inferred value. Using a `let` binding gives E0435, "attempt to use a non-constant value in a constant". Run-time sizes need a `Vec` or a slice.

  • N is passed to the function at run time like a hidden argument
  • You still need a separate impl or macro for each array length
  • The turbofish sum::<3> is mandatory whenever a const parameter is involved
  • A Vec<i32> can be passed where [i32; N] is expected because both hold i32s
  • Every std trait, including Default, is implemented for arrays of any length