skip to content

In Rust, how can a `Matrix<const R: usize, const C: usize>` type make multiplying a 2x3 matrix by another 2x3 matrix a compile error?

level: middleimportance: should knowfreq 30%

answer

  1. shape lives in the type
  2. shared inner dimension
  3. a third const parameter K
  4. mismatch is E0308

basics

~20 s

Give mul the signature fn mul<const K: usize>(&self, rhs: &Matrix<C, K>) -> Matrix<R, K>. The right side must have C rows, so a 2x3 times 2x3 call is a type mismatch (E0308), and the result's shape is computed in its type.

solid answer

~40 s

Put the dimensions in the type: `struct Matrix<const R: usize, const C: usize> { cells: [[f64; C]; R] }`. Then multiplication is `fn mul<const K: usize>(&self, rhs: &Matrix<C, K>) -> Matrix<R, K>`. The inner dimension `C` appears in both operands, so `Matrix<2, 3>` can only be multiplied by a `Matrix<3, K>`; passing a `Matrix<2, 3>` makes rustc report E0308 with "expected `3`, found `2`". The output type `Matrix<R, K>` is derived at compile time, and at run time the struct is just its cells: no stored dimensions and no shape check. This only works when the sizes are known at compile time; run-time sizes need a `Vec`-backed matrix with checks.

code

rust · 30 lines
rust
#[derive(Debug, Clone, Copy, PartialEq)]
struct Matrix<const R: usize, const C: usize> {
    cells: [[f64; C]; R],
}

impl<const R: usize, const C: usize> Matrix<R, C> {
    fn zero() -> Self {
        Matrix { cells: [[0.0; C]; R] }
    }

    fn mul<const K: usize>(&self, rhs: &Matrix<C, K>) -> Matrix<R, K> {
        let mut out = Matrix::<R, K>::zero();
        for i in 0..R {
            for j in 0..K {
                for k in 0..C {
                    out.cells[i][j] += self.cells[i][k] * rhs.cells[k][j];
                }
            }
        }
        out
    }
}

fn main() {
    let a = Matrix::<2, 3> { cells: [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] };
    let b = Matrix::<3, 2> { cells: [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]] };
    let c: Matrix<2, 2> = a.mul(&b);
    println!("{:?}", c.cells);
    println!("{}", std::mem::size_of::<Matrix<2, 3>>());
}

go deeper

for a junior

Recall that const generics put numbers into a type, so Matrix<2, 3> and Matrix<3, 2> are different types.

for a middle

Explain how reusing C in the right operand's type enforces the multiplication rule, how K is inferred, and that nothing is stored or checked at run time.

for a senior

Show the limits: sizes must be compile-time constants, each shape is a separate monomorphized copy, and run-time shapes need a different type.

for a principal

Decide where a codebase should switch from type-level shapes to run-time shapes, and where conversion between the two belongs.

## Dimensions as type parameters A **const generic parameter** lets a type be parameterised by a value. For a matrix, the natural values are the row and column counts: ```rust struct Matrix<const R: usize, const C: usize> { cells: [[f64; C]; R], } ``` `Matrix<2, 3>` and `Matrix<3, 2>` are now **different types**, just as `[f64; 2]` and `[f64; 3]` are. Every method can state the shape it needs and the shape it returns, and rustc checks those shapes during type checking, before any code runs. ## Writing multiplication Matrix multiplication needs the left operand's column count to equal the right operand's row count, and the result takes the left's rows and the right's columns. That rule maps directly onto a signature: 1. The `impl<const R: usize, const C: usize> Matrix<R, C>` block names the left operand's shape. 2. `mul` introduces one more const parameter, `K`, for the right operand's column count. 3. The parameter `rhs: &Matrix<C, K>` reuses `C`, so the shared dimension must match. 4. The return type `Matrix<R, K>` states the result's shape. ```rust fn mul<const K: usize>(&self, rhs: &Matrix<C, K>) -> Matrix<R, K> ``` Calling `a.mul(&b)` with `a: Matrix<2, 3>` and `b: Matrix<3, 2>` infers `K = 2` and returns `Matrix<2, 2>`. Calling `a.mul(&a)` asks rustc to match `Matrix<2, 3>` against `Matrix<3, _>`, and it reports **E0308 mismatched types**, pointing at the argument with "expected `3`, found `2`". The bug never reaches a test, let alone production. ## What exists at run time - **No stored dimensions**: `R` and `C` live only in the type. `size_of::<Matrix<2, 3>>()` is 48 bytes, exactly six `f64` values. - **No shape checks**: the loops use `R`, `C` and `K` as constants, so there is nothing to validate and the optimizer can unroll small loops. - **No heap**: `[[f64; C]; R]` is stored inline, so a `Matrix<4, 4>` can be `Copy` and lives on the stack or inside another struct. - **One copy per shape**: each combination of `R`, `C` and `K` used in the program is monomorphized separately, the usual cost of generics. ## Methods only some shapes have The same technique restricts methods to shapes where they make sense. An `impl` block can repeat a parameter to require a square matrix: ```rust impl<const N: usize> Matrix<N, N> { fn identity() -> Self { let mut cells = [[0.0; N]; N]; for i in 0..N { cells[i][i] = 1.0; } Matrix { cells } } fn trace(&self) -> f64 { (0..N).map(|i| self.cells[i][i]).sum() } } ``` - `Matrix::<3, 3>::identity()` compiles, and so does `trace` on it. - Calling `trace` on a `Matrix<2, 3>` is **E0599**, with the note "the method was found for `Matrix<N, N>`". - Element-wise addition can require the same shape on both sides simply by using `Matrix<R, C>` for both operands, whether as a method or through the operator traits. ## Where the approach stops | Situation | Const-generic `Matrix<R, C>` | `Vec`-backed matrix | |---|---|---| | Shape known when writing the code (4x4 transforms, 3-vectors) | checked by the type system | checked at run time | | Shape read from a file or user input | not possible | natural fit | | Mismatch detected | at compile time, E0308 | at run time, a panic or an `Err` | | Storage | inline array, no allocation | heap allocation | A const argument must be a compile-time constant. Writing `Matrix::<n, n>` where `n` is a `let` binding fails with **E0435**, "attempt to use a non-constant value in a constant". Game and graphics code, where 2x2, 3x3 and 4x4 shapes are fixed, is where the type-level version pays off; data-analysis code with arbitrary shapes keeps run-time dimensions. Some shape arithmetic is also out of reach on stable. A method such as `transpose` is fine because it only reorders the parameters (`fn transpose(&self) -> Matrix<C, R>`), but a signature that needs `R + 1` rows cannot be written, because inside a type a const parameter must appear on its own. That limit is a separate topic. ## Reading the error When a dimension mismatch fails, rustc's note shows both shapes, for example "expected reference `&Matrix<3, _>`, found reference `&Matrix<2, 3>`". The `_` is the `K` it has not pinned down yet. Reading that note is usually faster than reading the matrix code: the first number in the expected type is the column count of the left operand.

  • How would you write `transpose` for this `Matrix`?
    `fn transpose(&self) -> Matrix<C, R>`: build a `Matrix::<C, R>` and copy `cells[i][j]` into `cells[j][i]`. Only the order of the parameters changes, so no const arithmetic is needed and the signature compiles on stable.
  • What would you do if some matrices arrive with sizes read from a file?
    Keep a separate run-time type, such as a struct holding `rows`, `cols` and a `Vec<f64>`, whose `mul` checks the dimensions and returns a `Result`. Convert to the const-generic type only where the shape is known, for example with `TryFrom` that checks the dimensions once.

  • The matrix stores R and C as fields and compares them when multiplying
  • A dimension mismatch is caught by a panic on the first multiplication
  • Const generics can take sizes that are only known when the program starts
  • Matrix<2, 3> and Matrix<3, 2> are the same type holding differently shaped data
  • Shape-checked matrices need a heap allocation for their cells