🦀 Rust Intermediate

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).