Sub topic 6
Naming associated types: Self::Item and <T as Trait>::Item
This chapter assumes you can write a trait with an associated type, as in type Item;, and that you can read generic bounds like T: Iterator. It covers the three ways to name an associated type and when each one is required.
Three ways to write the same name
An associated type belongs to a trait, so you always name it through something that implements that trait. Rust gives you three spellings:
| Spelling | Where it works | Example |
|---|---|---|
| `Self::Name` | Inside a trait or one of its impls | `Option<&Self::Item>` |
| `T::Name` | When `T` is a generic parameter with a bound that has `Name` | `Option<I::Item>` |
| `<Type as Trait>::Name` | Anywhere | `<Vec<i32> as IntoIterator>::Item` |
The first two are shorthand. The third is the full form, called a fully qualified path. Its parts are the type, the trait, and the name, and it can't be misread.
Shorthand with a generic parameter
When a parameter has exactly one bound that provides Item, I::Item is enough:
fn largest<I>(iter: I) -> Option<I::Item>
where
I: Iterator,
I::Item: Ord,
{
iter.max()
}
fn main() {
println!("{:?}", largest(vec![3, 9, 4].into_iter()));
println!("{:?}", largest(["pear", "apple"].into_iter()));
}This prints Some(9) and then Some("pear"). The return type and the Ord bound both use I::Item. The compiler looks at the bounds on I, finds Iterator, and resolves the name.
Ambiguity and the full form
Shorthand fails when two traits in scope both declare an associated type with the same name. In that case T::Item has no single meaning, so the compiler reports an "ambiguous associated type" error. The fix is to say which trait you mean:
trait Source {
type Item;
fn get(&self) -> Self::Item;
}
trait Sink {
type Item;
fn put(&mut self, value: Self::Item);
}
struct Pipe {
input: i32,
output: Vec<i64>,
}
impl Source for Pipe {
type Item = i32;
fn get(&self) -> i32 {
self.input
}
}
impl Sink for Pipe {
type Item = i64;
fn put(&mut self, value: i64) {
self.output.push(value);
}
}
fn relay<T>(t: &mut T)
where
T: Source + Sink,
<T as Source>::Item: Into<<T as Sink>::Item>,
{
let value = t.get();
t.put(value.into());
}
fn main() {
let mut pipe = Pipe { input: 7, output: Vec::new() };
relay(&mut pipe);
println!("{:?}", pipe.output);
}The program prints [7]. In relay, T::Item would be ambiguous because T is both a Source and a Sink. The where clause therefore names each one: <T as Source>::Item is i32 for Pipe, and <T as Sink>::Item is i64. The bound says the source's item must convert into the sink's item.
Naming a concrete type's associated type
You can also write the full form with a concrete type. This is useful in annotations and type aliases:
type Elem = <Vec<u8> as IntoIterator>::Item;
fn main() {
let byte: Elem = 255;
println!("{}", byte);
}Elem is u8. The shorter Vec<u8>::Item is rejected with error E0223, "ambiguous associated type". A concrete type may implement many traits, so Rust won't guess which one you mean. The full form is the only way to write this.
Choosing a spelling
Using the full form when shorthand would work is always legal. It is just longer.
Common errors
- Writing
Vec<i32>::Itemand getting E0223. Use<Vec<i32> as IntoIterator>::Item. - Writing
T::ItemwhenThas two bounds that both defineItem. Qualify each use. - Forgetting the bound. In
fn f<T>() -> T::Item, nothing saysThas anItem, so the compiler reports that the associated type wasn't found. AddT: Iteratoror another trait that provides it. - Writing
Iterator::Itemwith no type. A trait alone doesn't pick an implementer.
Exercise
In a function fn pair<T: Source + Sink>(t: &T), why does the return type T::Item fail to compile, and how do you write the return type so that it means the Sink item?
Show answer
Both Source and Sink declare Item, so T::Item is ambiguous and the compiler reports an error. Write the return type as <T as Sink>::Item.