trait-concept
Rust Associated type equality constraints
A bound may require an associated type to equal a specific type. This lets generic code rely on that type, not just on the existence of the trait. Expected output (not executed): 12 Why: Item = u32 permits arithmetic with a known integer type. Common mistake: Writing only S: Source and assuming the associated Item is a number.
Formal Syntax & Structure
rust syntaxrust
S: Source<Item = u32>Working Example
Example Snippetrust
trait Source { type Item; fn read(&self) -> Self::Item; }struct Counter(u32);impl Source for Counter { type Item = u32; fn read(&self) -> u32 { self.0 } }fn doubled<S: Source<Item = u32>>(s: &S) -> u32 { s.read() * 2 }fn main() { println!("{}", doubled(&Counter(6))); }