trait-concept
Rust Generic traits
A generic trait includes a type argument in the implementation identity. One type may implement the trait for different arguments when the implementations do not overlap. Expected output (not executed): count 4 text ok Why: The argument selects which Accept implementation applies. Common mistake: Assuming only one implementation is allowed for a type regardless of trait arguments.
Formal Syntax & Structure
rust syntaxrust
trait Accept<T> { fn accept(&self, value: T); }Working Example
Example Snippetrust
trait Accept<T> { fn accept(&self, value: T); }struct Logger;impl Accept<u32> for Logger { fn accept(&self, n: u32) { println!("count {n}"); } }impl Accept<&str> for Logger { fn accept(&self, s: &str) { println!("text {s}"); } }fn main() { Logger.accept(4_u32); Logger.accept("ok"); }