Sub topic 16
Associated constants
This chapter assumes you can define and implement traits, write generic functions with trait bounds, and know what a const item is. An associated constant is a constant that belongs to a trait. Each implementing type supplies its own value.
Declaring and implementing a constant
Declare the constant inside the trait with const, a name, and a type. An implementation must provide the value unless the trait gives a default.
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!("{}", Triangle::SIDES + Square::SIDES);
}This prints triangle with 3 sides, shape with 4 sides, and 7.
SIDES has no default, so every implementation must set it. NAME has a default, so Square can leave it out. A default method such as describe reads the constants through Self::.
Using constants in generic code
A constant is tied to a type, not to a value. A generic function can therefore read it without having an instance. You name the type parameter and write T::SIDES.
trait Shape {
const SIDES: u32;
}
struct Triangle;
struct Square;
impl Shape for Triangle {
const SIDES: u32 = 3;
}
impl Shape for Square {
const SIDES: u32 = 4;
}
fn total_sides<A: Shape, B: Shape>() -> u32 {
A::SIDES + B::SIDES
}
fn main() {
println!("{}", total_sides::<Triangle, Square>());
}The compiler knows the concrete types at each call site. It can usually fold the constant into the generated code, as part of monomorphization.
Constants on a type without a trait
You can also put a constant in an inherent impl block. This is common for fixed values that belong to one type.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
impl Point {
const ORIGIN: Point = Point { x: 0, y: 0 };
}
fn main() {
println!("{:?}", Point::ORIGIN);
}Common errors
- Forgetting a required constant gives error E0046, "missing trait items".
- Writing
SIDESwithoutSelf::or a type prefix inside a method does not resolve. - Constants must be computable at compile time, so you can't use a value computed at run time.
Exercise
A trait Unit needs a symbol such as "m" or "kg" that is the same for every value of a type. Should this be an associated constant or a method, and can you store Vec<Box<dyn Unit>> if you use a constant?
Show answer
An associated constant fits, since the symbol depends only on the type: const SYMBOL: &'static str;. With a constant, Unit is not dyn compatible, so Vec<Box<dyn Unit>> does not compile. If you need trait objects, use a method fn symbol(&self) -> &'static str instead.