Associated Constants
An associated constant is a compile-time constant (const) declared inside a trait or impl block and accessed on the type or trait using path syntax (Type::CONSTANT).
Associated Constants in Inherent impl Blocks
An inherent impl block can define constants tied to the type's namespace:
struct PacketHeader {
version: u8,
payload_len: u16,
}
impl PacketHeader {
pub const MAGIC_BYTE: u8 = 0xA5;
pub const HEADER_SIZE: usize = 3;
}
fn main() {
println!(
"Magic: 0x{:X}, Size: {} bytes",
PacketHeader::MAGIC_BYTE,
PacketHeader::HEADER_SIZE
);
let hdr = PacketHeader {
version: 1,
payload_len: 128,
};
println!("v{}, len={}", hdr.version, hdr.payload_len);
}
Magic: 0xA5, Size: 3 bytes
v1, len=128
Associated Constants in Traits
A trait can declare an associated constant without a value (requiring each implementor to provide one) or with a default value (allowing implementors to inherit or override it):
trait FixedRecord {
const RECORD_LEN: usize;
const ALIGNMENT: usize = 1; // Default value
fn validate_slice(bytes: &[u8]) -> bool {
bytes.len() == Self::RECORD_LEN
}
}
struct UuidRecord;
impl FixedRecord for UuidRecord {
const RECORD_LEN: usize = 16;
}
struct PageHeader;
impl FixedRecord for PageHeader {
const RECORD_LEN: usize = 64;
const ALIGNMENT: usize = 8; // Overrides default
}
fn print_layout<T: FixedRecord>(name: &str) {
println!(
"{name}: len = {}, align = {}",
T::RECORD_LEN,
T::ALIGNMENT
);
}
fn main() {
print_layout::<UuidRecord>("UuidRecord");
print_layout::<PageHeader>("PageHeader");
println!("Valid 16-byte slice: {}", UuidRecord::validate_slice(&[0u8; 16]));
}
UuidRecord: len = 16, align = 1
PageHeader: len = 64, align = 8
Valid 16-byte slice: true
Standard Library Associated Constants
All primitive numeric types expose their range limits and bit widths as associated constants rather than standalone module constants:
| Constant | Example (u16) |
Meaning |
|---|---|---|
T::MIN |
u16::MIN (0) |
Smallest value representable by T |
T::MAX |
u16::MAX (65535) |
Largest value representable by T |
T::BITS |
u16::BITS (16) |
Size of T in bits (u32) |
f64::INFINITY / f64::NAN |
inf / NaN |
IEEE 754 special floating-point constants |
Effect on dyn Compatibility
Adding an associated constant to a trait makes the trait not dyn-compatible (unless the constant is gated with where Self: Sized), because a trait object (&dyn Trait) does not store associated constants in its vtable by default and Type::CONST requires a statically known concrete type.