Sub topic 2
Declaring and implementing an associated type
This chapter assumes you can define and implement traits, write generic functions with trait bounds, and read basic lifetime annotations. It covers the core mechanics of associated types: how to declare one, how to implement it, and how to use it in generic code. Bounds on associated types, the standard library traits, and the comparison with generic parameters each get their own chapter.
The problem associated types solve
Suppose you want a trait for collections that can hand back their first element. The trait needs to mention the element type, but the trait cannot know it. A stack of integers and a buffer of bytes have different element types.
One answer is to make the trait generic: trait Container<T>. That works, but every use of the trait must now spell out T. An associated type takes a different approach. The trait declares a placeholder name, and each implementation fills in the concrete type once.
Declaring an associated type
An associated type is a type alias declared inside a trait with the type keyword. Methods in the trait refer to it as Self::Name.
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}Here Item is the associated type. The declaration says: "every implementer of Container picks some type and calls it Item." The trait does not say which type. Self::Item means "the Item type of whatever type is implementing this trait."
You can use Self::Item in argument positions, in return types, and inside default method bodies. It is an ordinary type from the compiler's point of view, though an unknown one until an implementation supplies it.
Implementing an associated type
Every impl block for the trait must assign the associated type with type Name = ConcreteType;. The right-hand side may use the impl's own generic parameters.
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}
struct Stack<T> {
items: Vec<T>,
}
impl<T> Container for Stack<T> {
type Item = T;
fn first(&self) -> Option<&Self::Item> {
self.items.first()
}
}
fn main() {
let s = Stack { items: vec![10, 20, 30] };
println!("{:?}", s.first());
}This prints Some(10). In the impl, type Item = T; ties the associated type to the stack's element type. Inside the impl you can write the type as Self::Item or as T, and the two are the same type. The signature of first could equally say Option<&T>, and the compiler would accept it, because it checks that your signature matches the trait's signature after substituting Item = T.
Each implementing type chooses independently. A byte buffer can use a different Item for the same trait:
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
fn push_item(&mut self, item: Self::Item);
fn is_empty(&self) -> bool {
self.first().is_none()
}
}
struct Stack<T> {
items: Vec<T>,
}
struct Bytes(Vec<u8>);
impl<T> Container for Stack<T> {
type Item = T;
fn first(&self) -> Option<&T> {
self.items.first()
}
fn push_item(&mut self, item: T) {
self.items.insert(0, item);
}
}
impl Container for Bytes {
type Item = u8;
fn first(&self) -> Option<&u8> {
self.0.first()
}
fn push_item(&mut self, item: u8) {
self.0.insert(0, item);
}
}
fn head<C: Container>(c: &C) -> Option<&C::Item> {
c.first()
}
fn main() {
let mut s = Stack { items: vec![10, 20, 30] };
s.push_item(5);
let mut b = Bytes(Vec::new());
println!("{}", b.is_empty());
b.push_item(b'A');
println!("{:?} {:?} {}", head(&s), head(&b), b.is_empty());
}The program prints true, then Some(5) Some(65) false. Three details are worth noting:
push_itemtakesSelf::Itemas an argument, so the trait constrains inputs as well as outputs.Bytes::push_itemaccepts only au8.is_emptyis a default method. It is written once against the unknownSelf::Item, and every implementer inherits it. Its body never needs to know whatItemis.headis generic over anyContainer. Its return typeOption<&C::Item>is resolved separately for eachCit is called with.
How the compiler sees it
An associated type is not an extra generic parameter that callers supply. It is an output of the implementation. Given the type Stack<i32> and the trait Container, the compiler can look up exactly one impl and read Item from it.
This gives a rule that matters in practice: a type can implement a trait with an associated type only once. You cannot write two impl Container for Stack<i32> blocks with different Item types, because the compiler would not know which Item a call like s.first() should produce. The compiler reports this as error E0119, conflicting implementations. The one-impl rule is what lets inference work without annotations. Given a Stack<i32>, the item type is already determined.
Associated types inside generic code
In a generic function, C::Item is shorthand for <C as Container>::Item. You can use the short form when the bound makes the trait unambiguous. In fn head<C: Container>(c: &C) -> Option<&C::Item>, only one trait in scope could provide Item for C, so the compiler resolves it.
Inside the generic body, C::Item is opaque. You can store it, move it, and return it, but you cannot call methods on it or print it, because the bound C: Container says nothing about what Item can do. If you try, you get a "trait bound not satisfied" style error on the Item type. Adding bounds to Item is the subject of the next chapter.
Rules that trip people up
You must assign the type in every impl. A missing type Item = ...; produces error E0046, "not all trait items implemented, missing: Item".
The name must match the trait's declaration exactly. A typo such as type Itm = T; gives an error saying the type is not a member of the trait.
An associated type belongs to the trait, not to the struct. You cannot write Stack::Item on its own. To name it you need the trait, as in <Stack<i32> as Container>::Item. That path form is covered in a later chapter.
An impl cannot leave the type unresolved. type Item = T; is fine inside impl<T> ... because T is a parameter of the impl. But type Item = U; where U appears nowhere in the impl header is an error: the parameter is "unconstrained". The impl header must determine every type it uses.
| Mistake | What you see | Fix |
|---|---|---|
| Forgot `type Item = ...;` in an impl | E0046, missing `Item` | Add the assignment to the impl block |
| Wrote the name differently from the trait | The type is not a member of the trait | Match the trait's spelling |
| Two impls of the trait for the same type | E0119, conflicting implementations | Keep one impl, or use a generic trait parameter instead |
| Used `Item` alone inside a trait method | Cannot find type `Item` in this scope | Write `Self::Item` |
| Called a method on `C::Item` in generic code | The method is not found, or a trait bound is not satisfied | Add a bound on `C::Item` (next chapter) |
Associated types with default methods
A trait can hold both associated types and provided methods, as is_empty showed. Be aware that Rust does not allow a default for the associated type itself on stable Rust. The feature, called associated type defaults, is unstable. For now, every implementer assigns the type explicitly. Default method bodies work with Self::Item without needing to know it.
When to reach for one
Use an associated type when the trait has a single natural choice of the related type for each implementer. A stack holds one kind of element. An iterator yields one kind of item. A parser produces one kind of output. The type is determined by the implementer, and callers should not have to restate it.
Exercise
You write trait Shape { type Unit; fn area(&self) -> Self::Unit; } and implement it for struct Square(f64) with type Unit = f64;. A colleague then tries to add a second impl Shape for Square with type Unit = u32; so the area can also be reported as an integer. What happens, and why?
Show answer
The compiler rejects the second impl with E0119 (conflicting implementations). An associated type is chosen once per implementing type, so Square can have only one Unit. If a type needs several outputs, either use two different traits or methods, or make the trait generic (trait Shape<U>), which allows several impls for the same type with different U.
Exercise
Write a trait Source with an associated type Output and a method produce(&self) -> Self::Output. Implement it for struct Constant(i32) with Output = i32, and for struct Greeting(String) with Output = String that returns a clone of the string. Then write fn run<S: Source>(s: &S) -> S::Output and call it on both types.
Show answer
trait Source { type Output; fn produce(&self) -> Self::Output; } followed by impl Source for Constant { type Output = i32; fn produce(&self) -> i32 { self.0 } } and impl Source for Greeting { type Output = String; fn produce(&self) -> String { self.0.clone() } }. Then fn run<S: Source>(s: &S) -> S::Output { s.produce() }. Calling run(&Constant(7)) returns 7, and run(&Greeting("hi".to_string())) returns "hi".