Search CTRL + K

Associated Types

关联类型(associated types) 是将一个类型占位符和 trait 关联的方式,trait 的方法签名中就可以使用这些占位符类型。

pub trait MyTrait {
    type Item;

    fn hello(&self) -> Option<Self::Item>;


impl MyTrait for MyStruct {
    type Item = i32;

    fn hello(&self) -> Option<Self::Item> {


pub trait MyTrait<T> {
    fn hello(&self) -> Option<T>;

因为有关联类型的 trait 只能实现一次,而有泛型参数的 trait 可以给不同类型重复实现。因此看需求来选。

What is associated types?

Associated types connect a type placeholder with a trait such that the trait method definitions can use these placeholder types in their signatures.[1]

Why the Rust need associated types?

The implementor of a trait will specify the concrete type to be used instead of the placeholder type for the particular implementation. That way, we can define a trait that uses some types without needing to know exactly what those types are until the trait is implemented.[1:1]

Why adding associated types instead of using generics?

The difference is that when using generics, we must annotate the types in each implementation; because we can also implement Iterator<String> for Counter or any other type, we could have multiple implementations of Iterator for Counter. In other words, when a trait has a generic parameter, it can be implemented for a type multiple times, changing the concrete types of the generic type parameters each time. When we use the next method on Counter, we would have to provide type annotations to indicate which implementation of Iterator we want to use.

With associated types, we don’t need to annotate types because we can’t implement a trait on a type multiple times.[1:2]

  1. ↩︎ ↩︎ ↩︎