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. You should also have used Iterator in for loops.
The problem associated types solve
Suppose you want a trait for collections that can return their first element. The method signature needs a type for that element, but the trait cannot know it. A stack of integers returns i32, and a list of names returns String.
An associated type is a type placeholder declared inside a trait. Each implementation fills the placeholder with a concrete type. The trait stays general, and every implementer decides what the type is.
Declaring the type
You declare an associated type with the type keyword inside the trait body. Inside the trait, you refer to it as Self::Item.
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}This trait has one required type, Item, and one required method. The method returns a reference to an Item, wrapped in Option because the container may be empty.
Implementing the trait
An impl block must assign every associated type the trait declares. For a generic struct, the assigned type can use the struct's own type 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; says that a Stack<T> holds items of type T. The method body calls Vec::first, which returns Option<&T>. That matches Option<&Self::Item>, because Self::Item is T here.
Inside the impl you can write either Self::Item or T, since they are the same type. The trait declaration can only use Self::Item.
Different implementers, different types
A second implementer can choose a different Item. The trait definition doesn't change.
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}
struct Names {
list: Vec<String>,
}
struct Single(f64);
impl Container for Names {
type Item = String;
fn first(&self) -> Option<&String> {
self.list.first()
}
}
impl Container for Single {
type Item = f64;
fn first(&self) -> Option<&f64> {
Some(&self.0)
}
}
fn main() {
let n = Names { list: vec![String::from("Ada"), String::from("Grace")] };
println!("{:?} {:?}", n.first(), Single(2.5).first());
}This prints Some("Ada") Some(2.5). Each type has exactly one Container implementation, so each has exactly one Item.
One implementation, one type
That last point is the main design property of associated types. For a given implementing type, the associated type is determined. Names has one Item, so the compiler can work out Item from the receiver type alone. Callers never have to write it down.
The compiler also rejects a second implementation of the same trait for the same type, even with a different Item. If you need one type to implement a trait several times with different types, a generic trait parameter is the right tool. A later chapter compares the two.
Common errors
Two mistakes come up often when you start.
- Leaving out the type. If the
implhas notype Item = ...;line, the compiler reports error E0046, "not all trait items implemented, missing:Item". - Writing
ItemwithoutSelf::. Inside the trait, a bareItemis not in scope. The compiler reports "cannot find typeItemin this scope". WriteSelf::Item.
error[E0046]: not all trait items implemented, missing: `Item`Exercise
Write a trait Source with an associated type Output and a method produce(&self) -> Self::Output. Then implement it for struct Greeter; with Output = String. What does the impl need to contain besides the method?
Show answer
The impl must also assign the type: impl Source for Greeter { type Output = String; fn produce(&self) -> String { String::from("hello") } }. Without the type Output = String; line the compiler reports E0046.