trait-concept

Rust Trait objects with associated types

If a dyn-compatible trait exposes an associated type usable through the object, specify its required value when forming the object type. Implementations with different associated types cannot both satisfy the same equality constraint. Expected output (not executed): 18 Why: The object erases Gauge but retains Item = u32 in its interface. Common mistake: Omitting Item when it is required to determine the object type.

Formal Syntax & Structure

rust syntaxrust
&dyn Source<Item = u32>

Working Example

Example Snippetrust
trait Source { type Item; fn read(&self) -> Self::Item; }struct Gauge(u32);impl Source for Gauge { type Item = u32; fn read(&self) -> u32 { self.0 } }fn show(source: &dyn Source<Item = u32>) { println!("{}", source.read()); }fn main() { show(&Gauge(18)); }
Rust Reference