What are associated types vs generic parameters in Rust traits?
Answer
Associated types in traits define a placeholder type that an implementing type specifies once. The canonical example is Iterator: trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; }. An implementor says type Item = i32; — there is only one concrete Iterator implementation per type, and you refer to the item type as I::Item. Generic parameters on traits allow multiple implementations for the same type. For example, trait From<T> lets a type implement From<String>, From<i32>, etc. simultaneously. The rule of thumb: use associated types when there is only one sensible output type for a given implementation (Iterator, Deref), and generic parameters when you want to allow multiple implementations for different input types (From, Into).
Previous
What are lifetimes in structs and function signatures in Rust?
Next
What is interior mutability in Rust?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?