Sub topic 16
Associated constants
An associated constant is a named value that belongs to a trait or to a type, and each implementing type can set its own value. This chapter covers how to declare one, how to read it from generic code, and where it stops working.
It assumes you can write a trait and implement it for a type, use trait bounds on generic functions, and use const items. It also assumes you have seen Self inside an impl block.
Declaring an associated constant in a trait
A trait can list constants next to its methods. A constant with no value is required, so every implementor must supply one. A constant with a value is a default, and an implementor may override it.
trait Shape {
const SIDES: u32;
const NAME: &'static str = "shape";
fn describe(&self) -> String {
format!("{} with {} sides", Self::NAME, Self::SIDES)
}
}
struct Triangle;
struct Square;
impl Shape for Triangle {
const SIDES: u32 = 3;
const NAME: &'static str = "triangle";
}
impl Shape for Square {
const SIDES: u32 = 4;
}
fn main() {
println!("{}", Triangle.describe());
println!("{}", Square.describe());
println!("{}", <Square as Shape>::SIDES);
}This prints triangle with 3 sides, then shape with 4 sides, then 4.
Three details to notice:
Self::SIDESinside a default method refers to the constant of whichever type is implementing the trait. This works likeSelf::method()for associated functions.Squaredoes not defineNAME, so it gets the default"shape". Defaults work the same way as default methods, which the earlier chapter on default methods covered.<Square as Shape>::SIDESis the fully qualified form. You need it when the compiler cannot tell which trait you mean, for example when two traits both declare a constant calledSIDES.
Write the type of each constant out in full. For string constants, write &'static str.
Inherent associated constants
You do not need a trait to attach a constant to a type. An ordinary impl block can hold constants too. These are called inherent associated constants, and you read them as Type::NAME.
struct Packet;
impl Packet {
const HEADER_LEN: usize = 4;
const MAX_PAYLOAD: usize = 1024;
const MAX_TOTAL: usize = Self::HEADER_LEN + Self::MAX_PAYLOAD;
}
fn main() {
let header = [0u8; Packet::HEADER_LEN];
println!("{} {}", header.len(), Packet::MAX_TOTAL);
}This prints 4 1028.
Constants can refer to other constants in the same impl through Self::. They can also be used where Rust needs a compile-time value, such as the length of an array.
This is the usual way to avoid magic numbers. Name the value once and put it next to the type it describes.
Reading a constant from generic code
A trait constant is most useful when you have a type but no value of that type. A method needs a receiver, so T::method() only works for associated functions. A constant is simpler: T::NAME works directly.
trait Unit {
const SYMBOL: &'static str;
const METERS: f64;
}
struct Meters;
struct Kilometers;
impl Unit for Meters {
const SYMBOL: &'static str = "m";
const METERS: f64 = 1.0;
}
impl Unit for Kilometers {
const SYMBOL: &'static str = "km";
const METERS: f64 = 1000.0;
}
fn convert<A: Unit, B: Unit>(value: f64) -> String {
let result = value * A::METERS / B::METERS;
format!("{:.1} {} = {:.1} {}", value, A::SYMBOL, result, B::SYMBOL)
}
fn main() {
println!("{}", convert::<Kilometers, Meters>(1.5));
println!("{}", convert::<Meters, Kilometers>(250.0));
}This prints 1.5 km = 1500.0 m, then 250.0 m = 0.2 km.
Meters and Kilometers are empty structs. They exist only to carry constants. The caller picks the units with turbofish syntax (::<A, B>), and the compiler generates a separate copy of convert for each pair. Because of that, A::METERS is a known value in each copy, and the optimizer can fold the arithmetic. This is static dispatch, covered earlier in the series.
The limit on array lengths
You cannot write [u8; T::SIZE] inside a generic function and have SIZE come from a trait bound. Using a constant that depends on a generic parameter as an array length needs a feature called generic const expressions, which is not stable. A constant used as an array length works only when its value does not depend on a generic parameter.
There are two usual workarounds:
- Use a const generic parameter, such as
struct Buffer<const N: usize>, and take the length from there. - Use a
Vec<u8>and size it at run time withvec![0; T::SIZE].
Checking constants at compile time
Constants are evaluated by the compiler, so a failing assert! inside a constant becomes a compile error. You can use this to reject bad implementations.
trait Bounded {
const MAX: u32;
const VALID: () = assert!(Self::MAX > 0, "MAX must be positive");
fn limit() -> u32 {
let () = Self::VALID;
Self::MAX
}
}
struct Small;
struct Large;
impl Bounded for Small {
const MAX: u32 = 10;
}
impl Bounded for Large {
const MAX: u32 = 500;
}
fn main() {
println!("{} {}", Small::limit(), Large::limit());
}This prints 10 500. If you added an implementor with MAX = 0 and called limit() on it, the build would fail with a message that includes "MAX must be positive".
Two things matter here:
- A trait constant that depends on
Selfis only evaluated for a concrete type, after the generic code is instantiated. A problem therefore shows up when a bad type is used, not when the trait is declared. - The check runs only if some code mentions
Self::VALID. That is whylimitreads it. An implementor that never callslimitis never checked.
Constants and trait objects
A trait with an associated constant cannot be used as dyn Trait. A trait object has no concrete type at compile time, so Self::SIDES has nothing to resolve against. The dyn compatibility chapter lists the full rules. If you need the same information from a dyn value, add a method that returns it.
trait Shape {
const SIDES: u32;
fn sides(&self) -> u32 {
Self::SIDES
}
}This trait still has the constant, so it is still not dyn compatible. To use trait objects, drop the constant and keep only the method.
A middle path is to split the trait in two. Keep the dyn-compatible methods in one trait and put the constants in a second trait that generic code can use.
Choosing between related tools
| Need | Use | Why |
|---|---|---|
| A fixed value per type, read without an instance | Associated constant | `T::NAME` works in generic code and is known at compile time |
| A value that needs computation or varies per instance | Method | Methods take `&self` and can run code |
| A value that is a type, not a number | Associated type | Constants cannot hold types |
| A length that must size an array in generic code | Const generic parameter | Stable, and it works as an array length |
| A trait you need as `dyn Trait` | Method instead of constant | Associated constants make a trait not dyn compatible |
Common mistakes
- Writing
&strwithout a lifetime in older code. Prefer&'static str, which is accepted everywhere. - Calling
T::SIDESwhen two bounds both declareSIDES. Use<T as Shape>::SIDESto say which one. - Expecting a constant to have one memory address. A
constis inlined at each use. If you need a single location, use astatic, which a trait cannot declare. - Relying on the compile-time check without referencing the constant. An unused constant is never evaluated for that type.
Exercise
A trait Animal declares const LEGS: u32; and a method fn name(&self) -> String;. A teammate wants to store Vec<Box<dyn Animal>>. What goes wrong, and how can you fix it while keeping the leg count available?
Show answer
The trait is not dyn compatible, because the associated constant has no value for an unknown concrete type, so Box<dyn Animal> does not compile. Fix it by replacing the constant with a method such as fn legs(&self) -> u32;, or by moving LEGS into a second trait that is used only in generic code.
Exercise
Given trait Id { const ID: u32; } and struct A; struct B; with impl Id for A { const ID: u32 = 1; } and impl Id for B { const ID: u32 = 2; }, write a generic function sum_ids<X: Id, Y: Id>() -> u32 and say what sum_ids::<A, B>() returns.
Show answer
fn sum_ids<X: Id, Y: Id>() -> u32 { X::ID + Y::ID }. The call sum_ids::<A, B>() returns 3.