In Rust, what does a trait's associated const such as `const ID: u32;` offer over a method returning it, and where does it stop working?
answer
- a value per impl, not per instance
- readable as M::ID, no self
- const contexts for concrete types
- generic arrays and patterns refuse it
- no dyn, E0038
basics
~20 sAn associated const is a compile-time value each impl supplies, read as M::ID without an instance and usable in const contexts for concrete types. Generic code cannot use it as an array length or a pattern, and it rules out dyn.
solid answer
~50 s`trait Message { const ID: u32; }` makes every implementer supply a constant (or accept a default written in the trait), and the impl's value is reached through the type: `Ping::ID`, `M::ID` in generic code, or `<Upload as Message>::MAX_LEN`. Unlike `fn id(&self) -> u32` it needs no value of the type, and for a concrete type it is usable wherever a constant is: `[0u8; Ping::ID as usize]` or a `Ping::ID =>` match arm. Inside a generic function it stops there: `[u8; M::ID as usize]` is rejected (`generic parameters may not be used in const operations`) and `M::ID =>` as a pattern is E0158. A trait with an associated const is also not dyn compatible (E0038). Associated consts are evaluated only when referenced, generic ones after monomorphisation, so since Rust 1.79 a `const { assert!(M::ID != 0) }` block fails the build for exactly the instantiation that breaks it.
code
rust · 30 linestrait Message {
const ID: u32;
const MAX_LEN: usize = 256; // default, may be overridden
fn body(&self) -> &[u8];
}
struct Ping;
struct Upload(Vec<u8>);
impl Message for Ping {
const ID: u32 = 1;
fn body(&self) -> &[u8] { &[] }
}
impl Message for Upload {
const ID: u32 = 7;
const MAX_LEN: usize = 4096;
fn body(&self) -> &[u8] { &self.0 }
}
fn frame<M: Message>(m: &M) -> Vec<u8> {
assert!(m.body().len() <= M::MAX_LEN);
let mut out = M::ID.to_be_bytes().to_vec();
out.extend_from_slice(m.body());
out
}
fn main() {
println!("{:?}", frame(&Ping));
println!("{:?} {}", frame(&Upload(vec![9, 9])), <Upload as Message>::MAX_LEN);
}go deeper
Recall that a trait can declare const ID: u32; that each impl defines, and that you read it as Ping::ID without creating a value.
Explain how it differs from a method: no instance needed, usable in const contexts for concrete types, defaults allowed, but not callable through dyn.
Know the edges rustc enforces: generic array lengths and patterns refuse M::ID, E0038 blocks dyn, and evaluation is per instantiation, which inline const blocks turn into compile-time checks.
Adding an associated const to a published trait removes dyn use for every downstream user, so split static data into its own trait from the start.
## What an associated const is An **associated const** is a constant declared in a trait and defined by each impl. The declaration is `const NAME: Type;`; the definition in an impl looks like any `const` item: ```rust trait Message { const ID: u32; // every impl must define it const MAX_LEN: usize = 256; // a default an impl may override } impl Message for Ping { const ID: u32 = 1; } ``` An impl that leaves out `ID` is rejected with **E0046**, `not all trait items implemented, missing: ID`. An impl that is happy with `MAX_LEN = 256` writes nothing; one that needs more writes `const MAX_LEN: usize = 4096;`. Unlike associated types, associated consts may have defaults on stable. The value belongs to the **impl**, not to any instance. It is not stored in each `Ping` value and costs no memory per value; it behaves like a named constant that the compiler substitutes where it is used. ## What it gives you over a method | Need | `fn id(&self) -> u32` | `const ID: u32` | |---|---|---| | read it without a value of the type | needs a `self` (or a separate associated function) | `Ping::ID`, `M::ID` | | use it in a const context for a concrete type | only a `const fn` call can, and a trait method cannot be declared `const` (E0379) | `[0u8; Ping::ID as usize]`, `Ping::ID =>` in a `match` | | per-impl default with override | default method body | default value in the trait | | call through `&dyn Message` | yes | no: the trait is not dyn compatible | Typical uses are a wire-protocol tag per message type, a fixed buffer size per codec, a per-type name for logging, and the numeric constants std puts on every integer type, such as `u32::BITS` (an inherent associated const, not a trait one). In generic code the const is reached through the type parameter: `fn frame<M: Message>(m: &M)` can write `M::ID.to_be_bytes()` and compare against `M::MAX_LEN`, and each instantiation sees its own impl's values. ## Where it stops working Three limits come up in practice, and rustc 1.99 reports each one clearly: 1. **Generic array lengths.** `fn header<M: Message>() -> [u8; M::ID as usize]` is rejected with `generic parameters may not be used in const operations`. Inside generic code, stable Rust sizes an array only with a bare const parameter or a constant expression that does not depend on generic parameters; an expression built from a type parameter's const needs an unstable feature. The same expression with a concrete type, `[0u8; Ping::ID as usize]`, compiles. 2. **Patterns.** In a generic function, `match id { M::ID => ..., _ => ... }` is **E0158**, `constant pattern cannot depend on generic parameters`. With a concrete type, `Ping::ID =>` is a valid constant pattern. In generic code, compare with `if id == M::ID` instead. 3. **Trait objects.** The Reference's dyn-compatibility rules say a dyn-compatible trait must not have any associated constants. `&dyn Message` therefore fails with **E0038**, and rustc's note says the trait is not dyn compatible because it contains associated const `ID`, suggesting moving it to another trait. The usual fix is exactly that: keep the const on a separate trait (or replace it with a method) so the object-safe part can still be used as `dyn`. ## When the value is evaluated The Reference states that associated constant definitions undergo constant evaluation **only when referenced**, and that definitions involving generic parameters are evaluated **after monomorphisation**. Two consequences: - A const in an impl that would panic during evaluation only breaks the build if something uses it. - A check on a generic const runs once per instantiation. An **inline const block**, stable since Rust 1.79, makes that a compile-time assertion: ```rust fn check<M: Message>() -> u32 { const { assert!(M::ID != 0, "message ID 0 is reserved") }; M::ID } ``` Calling `check::<Ping>()` where `Ping::ID` is 0 fails with **E0080**, `evaluation panicked: message ID 0 is reserved`, and rustc notes that the error arose while instantiating `fn check::<Ping>`. A plain `assert!` in the body would compile and panic at run time instead. ## Choosing between a const and a method - Choose an associated const when the value is a property of the type, known at compile time, and you want to use it without an instance or in a const context. - Choose a method when the value depends on the instance, must be computed at run time, or the trait must stay usable as `dyn`. - Keep both apart when you need both: a small trait with the const for static use, and the methods in a dyn-compatible trait.
- How do you keep a Rust trait usable as `dyn` when some implementers also need a compile-time `ID`?Split it. Put the dispatchable methods in one trait and the `const ID: u32;` in a second trait, so `&dyn Message` works while generic code bounds on both (`M: Message + Tagged`). A method such as `fn id(&self) -> u32` is the alternative when the value only needs to be available at run time.
- Why does a Rust associated const that panics during evaluation not always break the build?Associated const definitions are evaluated only when referenced, and generic ones after monomorphisation. An impl's const that is never used is never evaluated, so its panic never fires; the build breaks at the first use, or, for a generic const, at the first instantiation whose values make it panic, reported as E0080.
- An associated const is stored inside every value of the implementing type.
- M::ID can size an array inside a generic function on stable Rust.
- A trait with an associated const can still be used as dyn Trait.
- Trait associated consts cannot have a default value.
- A const assertion on M::ID fires as soon as the generic function is defined.
Assumes Rust 1.99; associated consts are long stable, while the inline const block used for the per-instantiation compile-time check is stable since 1.79.