On stable Rust, why do `struct A<const X: f32>` and a return type `[u8; N + 1]` using a const parameter `N` both fail to compile?
answer
- min const generics
- integers, bool and char only
- standalone in types
- post-monomorphization assertion
basics
~20 sStable const parameters may only be integers, bool or char, so f32 is forbidden as a const parameter type. Inside a type a const parameter must stand alone, so rustc rejects the arithmetic in N + 1.
solid answer
~40 sStable Rust ships the minimal form of const generics, and both rules come from that. First, a const parameter's type must be an integer type, `bool` or `char`; `f32`, `&'static str` or a struct gets "`f32` is forbidden as the type of a const generic parameter", because the general form (`adt_const_params`) is still unstable. Second, in a type or array-repeat position a const parameter must appear alone, as `N` or `{N}`; `[u8; N + 1]` fails with "generic parameters may not be used in const operations" (full expressions are the unstable `generic_const_exprs`). The usual workaround is a second parameter `M` plus an inline `const { assert!(M == N + 1) }` (inline const is stable since Rust 1.79), which fails when the function is instantiated with wrong sizes.
code
plaintext · 7 lineserror: generic parameters may not be used in const operations
--> l4.rs:1:52
|
1 | fn push<const N: usize>(a: [u8; N], x: u8) -> [u8; N + 1] { todo!() }
| ^ cannot perform const operation using `N`
|
= help: const parameters may only be used as standalone arguments here, i.e. `N`go deeper
Recall that const parameters on stable may only be integers, bool or char.
Explain that inside a type a const parameter must stand alone, so arithmetic like N + 1 is rejected, and how braces work for const arguments at call sites.
Show the inline const assertion workaround, explain why it is a post-monomorphization error that cargo check misses, and spot the exhaustive-impl trap.
Judge whether a design that needs const arithmetic should wait for nightly features, take a second parameter with an assertion, or move the size to run time.
## Two restrictions in the stable design Const generics stabilised in Rust 1.51 in a deliberately **minimal** form, and both errors in the question come straight from its two main limits. Each has a fuller design behind an unstable feature gate on nightly, which stable code cannot use. | Limit | Stable rule | Error rustc 1.99 prints | Unstable feature that lifts it | |---|---|---|---| | Parameter type | integer types, `bool`, `char` | "`f32` is forbidden as the type of a const generic parameter" | `adt_const_params` | | Use inside a type | the parameter must stand alone | "generic parameters may not be used in const operations" | `generic_const_exprs` | | Type of the parameter | cannot depend on another generic | E0770, "the type of const parameters must not depend on other generic parameters" | none on stable | ## Which types a const parameter may have The Reference lists the allowed types exactly: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `char` and `bool`. Everything else is rejected with a note, "the only supported types are integers, `bool`, and `char`". That excludes: - **Floats** such as `f32` and `f64`. Float equality is not reflexive (`NaN != NaN`), while the compiler must be able to decide whether two types such as `A<x>` and `A<y>` are the same. - **References** such as `&'static str`, rejected with the same "forbidden as the type of a const generic parameter" error. - **User types**, even a `#[derive(PartialEq, Eq)]` struct of two `usize` fields. - **Types that depend on other generics**: `fn f<T, const N: T>()` is E0770. When a design wants a "struct-valued" parameter, the stable answer is several integer parameters (`Matrix<const R: usize, const C: usize>`), or a `bool` or small integer for each flag. ## Where a const parameter may appear Inside function bodies a const parameter behaves like a `const` item: `let doubled = N * 2;` is fine, and so is `const LEN: usize = N * 4;` as an associated const in an `impl` block. The restriction is narrower: **in a type or an array repeat expression**, the parameter must appear alone, as `N` or `{N}`. So: 1. `[u8; N]` and `Foo<{ N }>` compile. 2. `[u8; N + 1]`, `[u8; { N * 2 }]` and `[0; N - 1]` do not; braces do not help. 3. The help line says "const parameters may only be used as standalone arguments here, i.e. `N`". ## The usual workaround When the output length really is `N + 1`, add a second parameter and **assert** the relationship in an inline const block, stable since **Rust 1.79**: ```rust fn push<const N: usize, const M: usize>(a: [u8; N], x: u8) -> [u8; M] { const { assert!(M == N + 1, "output must be one longer") }; let mut out = [0u8; M]; out[..N].copy_from_slice(&a); out[N] = x; out } ``` The caller writes `let b: [u8; 4] = push([1, 2, 3], 9);`. A wrong length, `[u8; 5]`, fails with **E0080**, "evaluation panicked: output must be one longer", plus a note that it happened "while instantiating `fn push::<3, 5>`". This is a **post-monomorphization error**: it fires only when code generation instantiates that call, so `cargo check` passes and `cargo build` fails. Other options are returning a `Vec<u8>` or redesigning so the output length is the parameter. ## A trap with exhaustive impls Trait solving ignores the fact that a finite type like `bool` has been fully covered: - `impl Bar for Foo<true> {}` and `impl Bar for Foo<false> {}` together cover every value. - Yet `fn g<const B: bool>() { needs_bar(Foo::<B>) }` fails with **E0277**, "the trait bound `Foo<B>: Bar` is not satisfied". - The Reference states that exhaustiveness of impls over const values is not considered. The fix is a single `impl<const B: bool> Bar for Foo<B>`, branching on `B` inside if needed. ## Small rules worth knowing - Const parameters may have defaults on types, `struct Buf<const N: usize = 16>`, stable since 1.59. - A computed const argument needs braces: `f::<{ C + 1 }>()`; a literal or a single path such as `f::<C>()` does not. - When a name could be a type or a const, rustc resolves it as a type; braces force the const reading.
- Why does `cargo check` accept a call that `cargo build` rejects with the inline const assertion?The assertion is evaluated per instantiation, during monomorphization, which happens when code is generated. `cargo check` stops after type checking and never instantiates `push::<3, 5>`, so it never evaluates that const block. Keep a `cargo build` or `cargo test` in CI to catch these errors.
- How do you express a configuration flag with a const parameter when floats and strings are banned?Use `bool` or an integer: `struct Logger<const VERBOSE: bool>` or `struct Retry<const MAX: u8>`. For anything richer, such as a name or a ratio, use a marker type implementing a trait with associated consts, which may be `&'static str` or `f64`.
- Any type that derives PartialEq and Eq can be a const parameter on stable
- Wrapping N + 1 in braces makes it legal as an array length
- Implementing a trait for Foo<true> and Foo<false> covers every Foo<B>
- A const parameter's type can be another generic parameter, as in const N: T
- An inline const assertion in a generic function is checked by cargo check
Assumes Rust 1.99 on the 2024 edition; the parameter-type and standalone-use limits are unchanged since const generics stabilised in 1.51, and the inline const workaround needs 1.79.