Rust
Associated type
Define an associated type in a trait.
Associated types
An associated type is a type placeholder named inside a trait, decided once by each implementation. Iterator::Item is the best-known example:
trait Kap {
type Oge;
fn al(&self, i: usize) -> Option<&Self::Oge>;
}
struct Liste(Vec<String>);
impl Kap for Liste {
type Oge = String;
fn al(&self, i: usize) -> Option<&String> {
self.0.get(i)
}
}
The difference from a generic parameter (trait Kap<T>): a type can implement the trait only once, and the type doesn't need to be written when using it.
Bounding with an associated type
In generic code the associated type is reached as T::Oge and can be bounded:
fn ilk_yaz<K>(k: &K)
where
K: Kap,
K::Oge: std::fmt::Debug,
{
println!("{:?}", k.al(0));
}
// a bound requiring a specific element type:
fn metinler<K: Kap<Oge = String>>(k: &K) { .. }
Exercise Container trait
Write the Kap trait above and the Liste implementation. Print the results of al(1) and al(5) for Liste(vec!["a".into(), "b".into()]) with {:?}, separated by a space.
Show example solution
trait Kap {
type Oge;
fn al(&self, i: usize) -> Option<&Self::Oge>;
}
struct Liste(Vec<String>);
impl Kap for Liste {
type Oge = String;
fn al(&self, i: usize) -> Option<&String> {
self.0.get(i)
}
}
fn main() {
let l = Liste(vec!["a".into(), "b".into()]);
println!("{:?} {:?}", l.al(1), l.al(5));
}
Test yourself
-
When is a generic parameter chosen over an associated type?
- Always
- Never
- For performance
- When it makes sense for a type to implement the trait for several types (like From<T>)
Show answer
When it makes sense for a type to implement the trait for several types (like From<T>) — String implements both From<&str> and From<char>; an iterator has a single Item type.
-
Set the associated type
impl Kap for Liste {
type ____ = String;
fn al(&self, i: usize) -> Option<&String> { self.0.get(i) }
}
Show answer
impl Kap for Liste {
type Oge = String;
fn al(&self, i: usize) -> Option<&String> { self.0.get(i) }
}
-
Syntax and meaning
- type Oge;
- Declaration
- type Oge = String;
- Set in the impl
- K::Oge
- Access in generic code
- Kap<Oge = String>
- Equality bound
Next lesson: Associated constant