Sub topic 6
Naming associated types: Self::Item and <T as Trait>::Item
This chapter assumes you can define and implement traits, write generic functions with trait bounds, and declare an associated type with type Item;. It covers the ways to write the name of an associated type, when each one works, and what to do when the compiler says a name is ambiguous.
Why associated types need a path
An associated type belongs to a trait, not to a type on its own. A bare name like Item therefore means nothing in most places. To use it, you tell the compiler which type to look at and which trait defines the name. Rust has three spellings for this, from shortest to most explicit:
| Form | Where it works | What it means |
|---|---|---|
| `Self::Item` | Inside a trait definition or an impl | The `Item` of the trait being defined, or of one of its supertraits |
| `T::Item` | Where `T` is a generic parameter with bounds | The `Item` of whichever bound on `T` declares it, if exactly one does |
| `<T as Trait>::Item` | Anywhere | The `Item` that `T` gets from `Trait`, with no guessing |
The first two are shorthand. The third is the full form, called a fully qualified path.
Self::Name inside traits and impls
Inside a trait, Self stands for the type that will implement it. Self::Item is the associated type that implementer chooses. You use it in method signatures and default method bodies:
use std::fmt::Debug;
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
fn put(&mut self, item: 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 put(&mut self, item: Self::Item) {
self.items.push(item);
}
}
fn first_label<C>(c: &C) -> String
where
C: Container,
C::Item: Debug,
{
format!("first = {:?}", c.first())
}
fn main() {
let mut s = Stack { items: vec![10] };
s.put(20);
println!("{}", first_label(&s));
}The program prints first = Some(10).
In the impl, Self::Item and T are the same type, because the impl says type Item = T;. Both spellings compile. Writing Self::Item keeps the method signature identical to the trait's, which makes the impl easier to compare with the trait.
Self::Item also works through supertraits. If you write trait Tracked: Iterator, then Self::Item inside Tracked refers to Iterator::Item. The compiler follows the supertrait chain to find the name.
T::Name in generic code
In a generic function, C::Item reads naturally, and the first_label function above uses it. The compiler looks at the bounds on C, finds that Container declares Item, and resolves the name. The same shorthand works in struct fields and impl blocks:
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
fn put(&mut self, item: 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 put(&mut self, item: Self::Item) {
self.items.push(item);
}
}
struct Logged<C: Container> {
inner: C,
last_put: Option<C::Item>,
}
impl<C> Logged<C>
where
C: Container,
C::Item: Clone,
{
fn put(&mut self, item: C::Item) {
self.last_put = Some(item.clone());
self.inner.put(item);
}
}
fn main() {
let mut l = Logged {
inner: Stack { items: vec![1] },
last_put: None,
};
l.put(2);
println!("{:?} {:?}", l.last_put, l.inner.first());
}The program prints Some(2) Some(1).
Two details matter here:
- The struct
Logged<C: Container>declares the boundC: Containeron the struct itself. Without it,C::Itemhas no trait to resolve against, and the compiler rejects the field type. C::Item: Cloneis a bound on the associated type, not onC. You can place bounds on any path this way. The previous chapter's bounds likeI: Iterator<Item = u32>are a compact form of the same idea.
When the short form is ambiguous
T::Name fails when two bounds on T both declare an associated type with that name. The compiler will not pick one for you. Here two traits both define Output:
#[derive(Debug)]
struct Square(u32);
trait Shape {
type Output;
fn area(&self) -> Self::Output;
}
trait Scale {
type Output;
fn scale(&self, k: u32) -> Self::Output;
}
impl Shape for Square {
type Output = u32;
fn area(&self) -> u32 {
self.0 * self.0
}
}
impl Scale for Square {
type Output = Square;
fn scale(&self, k: u32) -> Square {
Square(self.0 * k)
}
}
fn both<T: Shape + Scale>(x: &T) -> (<T as Shape>::Output, <T as Scale>::Output) {
(x.area(), x.scale(2))
}
fn main() {
let sq = Square(3);
let area: <Square as Shape>::Output = Shape::area(&sq);
let bigger: <Square as Scale>::Output = sq.scale(2);
println!("{} {:?}", area, bigger);
println!("{:?}", both(&sq));
}The program prints two lines: 9 Square(6) and (9, Square(6)).
If you wrote T::Output in the return type of both, the compiler would report error E0221, "ambiguous associated type Output in bounds of T". The fix is to name the trait with <T as Shape>::Output. Read it as "the Output that T has when viewed as a Shape."
Concrete types always need the full path
For a concrete type, there is no shorthand. Square::Output does not compile, even if only one trait gives Square an Output. The compiler reports E0223, "ambiguous associated type", because a type can implement any number of traits, including ones added later by other crates. You write the trait:
use std::fmt::Display;
fn join<I>(iter: I) -> String
where
I: IntoIterator,
I::Item: Display,
{
let mut out = String::new();
for (i, x) in iter.into_iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
out.push_str(&x.to_string());
}
out
}
fn main() {
let n: <Vec<i32> as IntoIterator>::Item = 7;
println!("{}", n);
println!("{}", join(vec![1, 2, 3]));
println!("{}", join(["a", "b"]));
}The program prints 7, then 1, 2, 3, then a, b.
The annotation <Vec<i32> as IntoIterator>::Item is the type i32. In real code you would rarely write this out for a concrete type, because you could just write i32. The form matters most in macros and generated code, and in generic code where the concrete type is a parameter.
Calling methods with the same syntax
The <Type as Trait>::name syntax also selects between methods. If a type implements two traits that each define a method called describe, then value.describe() is ambiguous. You can write either of these:
Trait::describe(&value), which lets the compiler infer the type from the argument.<Type as Trait>::describe(&value), which states both the type and the trait.
The Shape::area(&sq) call in the earlier example uses the first style. The second style is required for functions that take no self, such as constructors. For example, <Square as Default>::default() works even when other traits in scope also define default.
Nested paths
A path can contain other paths. IntoIterator declares two associated types: Item, and IntoIter, which is bounded by Iterator<Item = Self::Item>. So for a generic I: IntoIterator, the following three types are the same:
I::Item<I as IntoIterator>::Item<<I as IntoIterator>::IntoIter as Iterator>::Item
The compiler knows the third equals the first because of the bound declared on IntoIter. You normally write the first form. The long form appears in compiler error messages, so it helps to be able to read it from the inside out: first find the innermost <I as IntoIterator>::IntoIter, then take that type's Item as an Iterator.
Common errors
- E0221, ambiguous associated type in bounds. Two bounds on
Tdefine the same name. Use<T as Trait>::Name. - E0223, ambiguous associated type. You wrote
Type::Nameon a concrete type. Use<Type as Trait>::Name. - E0220, associated type not found. The name does not exist on any bound of
T, often because you forgot the bound. AddT: Trait, or check for a spelling difference between the trait and your path. - Missing bound on a struct.
struct W<C> { x: C::Item }fails becauseChas no trait to resolve against. Put the bound on the struct:struct W<C: Container> { ... }.
Summary of rules
- Use
Self::Nameinside traits and impls. - Use
T::Namefor a genericTwhen exactly one bound declaresName. - Use
<T as Trait>::Namewhen two bounds declare the same name, or whenever the type is concrete. - Put the trait bound on any struct or impl whose fields or signatures use
C::Name.
Exercise
A function is declared as fn run<T: Iterator + Default>(x: T) -> Vec<T::Item>. It compiles. Then you add a second bound, T: Iterator + Sequence, where your own trait Sequence also declares type Item;. The return type now fails with E0221. Rewrite the return type so it compiles, and say which Item you chose.
Show answer
Write the return type as Vec<<T as Iterator>::Item> to use the iterator's items, or Vec<<T as Sequence>::Item> to use your trait's. T::Item is ambiguous because both bounds declare Item, so the compiler needs the trait name to pick one.
Exercise
Why does let v: Vec<i32>::Item = 5; fail, and what is the correct way to write the type of the items produced by Vec<i32> when it is used as an IntoIterator?
Show answer
A concrete type has no shorthand for associated types, because it may implement many traits that declare the same name. The compiler reports E0223. The correct form is <Vec<i32> as IntoIterator>::Item, which is i32.