trait-concept

Rust Associated types

An associated type gives an implementation a named output or related type. For a fixed implementing type and fixed trait arguments, the implementation determines this type. Expected output (not executed): 9 Why: Counter chooses u32 as Item, and its method must return that type. Common mistake: Trying to select a different Item for the same trait implementation at each call.

Formal Syntax & Structure

rust syntaxrust
trait Source { type Item; fn read(&self) -> Self::Item; }

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) -> Self::Item { self.0 }}fn main() { println!("{}", Counter(9).read()); }
Rust Reference