关联类型与泛型关联类型(GAT 简介)

上一节练习答案要点

上一节留了三道题,对照一下你的答案:

  1. &mut self 做接收者的方法是对象安全的。对象安全的三条规则只看这三件事:方法不能返回 Self、不能有泛型参数、trait 不能要求 Self: Sized。scale(&mut self, factor: f64) 三条都没踩,所以没问题。调用时用 for s in &mut shapes { s.scale(2.0); },&mut Box<dyn Shape> 会自动解引用成 &mut dyn Shape,再统计面积就能看到放大后的结果。
  2. 加上 fn duplicate(&self) -> Self 之后,Box<dyn Shape> 编译不过,报错是 E0038: the trait Shape cannot be made into an object,因为方法返回了 Self,虚表建不起来。改成 fn duplicate(&self) -> Box<dyn Shape> 就能编译:返回的还是“一个实现了 Shape 的东西”,但类型固定了。
  3. 改成 Vec<&dyn Shape> 时,图形要先声明成具名变量(比如 let c = Circle { radius: 2.0 };),再把 &c、&r 放进 Vec,因为借用必须有个活得比 Vec 久的“主人”。两种写法的区别:Box 是拥有,Vec 可以被移动、返回,里面的图形跟着走;&dyn 是借用,不经过堆分配,但图形变量必须先存在、且活得比 Vec 久,Vec 不能独自带走它们。

学习目标

读完这一节,你会:说出关联类型是什么、它和泛型参数的区别;会给 trait 定义关联类型,并在实现里把它定下来;会用 Box<dyn Iterator<Item = i32>> 这种写法约束 trait 对象里的关联类型;理解为什么普通 Iterator 返回不了借用自迭代器自身数据的引用;会写一个最简单的泛型关联类型(GAT),知道它在 Rust 1.65 稳定、现在能直接用。

核心概念

从 Iterator::Item 说起

你一直在用 Iterator,只是没注意过它肚子里藏了一个类型。打开标准库,Iterator 的定义大概是这样:

1
2
3
4
pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

type Item; 就是关联类型(associated type):trait 里先占一个位置,不写死具体是什么类型,留给实现者来定。next 返回 Option<Self::Item>——Self::Item 的意思是“实现这个 trait 的那个类型所指定的 Item”。

自己写一个迭代器就明白了。写一个从 1 数到 max 的计数器:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
struct Counter {
    count: u32,
    max: u32,
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.count >= self.max {
            None
        } else {
            self.count += 1;
            Some(self.count)
        }
    }
}

fn main() {
    let c = Counter { count: 0, max: 5 };
    for n in c {
        print!("{} ", n);
    }
    println!();
    // 既然是 Iterator,适配器都能用
    let c2 = Counter { count: 0, max: 5 };
    let doubled: Vec<u32> = c2.map(|x| x * 2).collect();
    println!("{:?}", doubled);
}

输出:

1
2
1 2 3 4 5
[2, 4, 6, 8, 10]

impl Iterator for Counter 这一行里,type Item = u32; 就是在给关联类型“交卷”:这个迭代器产出的元素是 u32。map、collect 这些适配器都是在 Iterator 上定义的通用方法,它们只认 Self::Item,不用知道具体是哪个类型——collect 能把 Counter 收进 Vec<u32>,靠的就是 Item = u32 这个约定。

标准库里到处都是关联类型。Add trait 长这样:

1
2
3
4
pub trait Add<Rhs = Self> {
    type Output;
    fn add(self, rhs: Rhs) -> Self::Output;
}

1 + 2 得到 i32,1.5 + 2.5 得到 f64,靠的都是实现者给 Output 交的卷:impl Add for i32 里 type Output = i32;,impl Add for f64 里 type Output = f64;。你写的 a + b 能是什么类型,编译器查 Output 就知道。

关联类型和泛型参数,差在哪

第 8 章学过泛型参数,很多人第一反应是:Iterator 干嘛不写成 trait Iterator<T>,next 返回 Option<T>?两者都能表达“产出某种元素”,差别在一个类型能实现几次。

泛型参数是 trait 的一部分:Iterator<i32> 和 Iterator<String> 是两个不同的 trait,一个类型可以同时实现两个。关联类型不是 trait 的一部分:Iterator 只有一个,Counter 实现了一次 Iterator,Item 就只有一个值——Counter 产出的元素要么是 u32,要么是别的,不可能既是 u32 又是 String。

这正好对应两种不同的现实:

  • 一个实现只有一种自然答案,用关联类型。计数器产出的元素类型是它自己决定的,调用方没必要每次都指明,也没道理让同一个计数器同时产出两种元素。Iterator、Add 的 Output 都是这种。
  • 一个实现可能有多种答案,调用方要选,用泛型参数。比如 From<T>:String 既能 From<&str> 又能 From<char>,From 后面的 T 就是调用方选的。

选错的代价很具体:如果 Iterator 用泛型参数定义,fn sum<I: Iterator<i32>>(it: I) 这样的签名里,调用方每次都要写一遍 i32;而关联类型版写 fn sum<I: Iterator<Item = i32>>(it: I)——不,还是要写 Item = i32。真正的差别在使用方:let v: Vec<_> = counter.collect(),collect 的目标类型从 Item 推导,调用方什么都不用写。更重要的是语义:Counter 这个类型只产出 u32,这是它的内在属性,不是调用方每次传参决定的。

判断用哪个,有个简单的口诀:如果这个类型是实现者自己说了算、调用方没得选,就用关联类型;如果调用方每次使用时都可能换一个,就用泛型参数。

给关联类型加约束

关联类型也可以带约束,写法是把约束写在 type 声明后面:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
trait Container {
    type Item: std::fmt::Debug;
    fn get(&self, index: usize) -> Option<&Self::Item>;
    fn count(&self) -> usize;
}

struct Bag<T> {
    items: Vec<T>,
}

impl<T: std::fmt::Debug> Container for Bag<T> {
    type Item = T;

    fn get(&self, index: usize) -> Option<&Self::Item> {
        self.items.get(index)
    }

    fn count(&self) -> usize {
        self.items.len()
    }
}

fn show_first<C: Container>(c: &C) {
    match c.get(0) {
        Some(item) => println!("第一个:{:?},共 {} 个", item, c.count()),
        None => println!("空的,共 0 个"),
    }
}

fn main() {
    let bag = Bag {
        items: vec!["苹果", "香蕉", "橙子"],
    };
    show_first(&bag);
    let nums = Bag { items: vec![10, 20, 30] };
    show_first(&nums);
    let empty = Bag::<i32> { items: vec![] };
    show_first(&empty);
}

输出:

1
2
3
第一个:"苹果",共 3 个
第一个:10,共 3 个
空的,共 0 个

type Item: std::fmt::Debug; 的意思是:谁实现 Container,谁就要保证自己的 Item 能用 {:?} 打印。于是 show_first 里可以直接 {:?} 打印取出来的元素,不用再给泛型参数 C 另写一堆约束。注意 impl<T: std::fmt::Debug> Container for Bag<T> 这一行:Item = T,而 Container 要求 Item: Debug,所以 T 也必须满足 Debug,实现那一行就要把这个约束写出来——编译器会检查,漏了就报错。

同一个 trait 可以有多个关联类型,比如一个图(graph)trait 可以同时定 Node 和 Edge;约束也可以叠多个,type Item: Clone + std::fmt::Debug; 这样写。关联类型之间还能互相引用,比如 type Iter: Iterator<Item = Self::Item>;——一个容器 trait 可以声明“我的迭代器类型”,并要求它产出的元素就是我的元素类型。

trait 对象里的关联类型:必须定下来

上一节讲过,Box<dyn Iterator> 这样写是编不过的:

1
let it: Box<dyn Iterator> = Box::new(0..5); // 编译失败

编译器会说关联类型 Item 的值必须指明。原因很实在:next 返回 Option<Self::Item>,Item 不定下来,调用 next 时编译器连返回值的类型都不知道。写法是在 trait 对象后面用 Item = i32 把它定死:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
fn print_all(iter: impl Iterator<Item = i32>) {
    for x in iter {
        print!("{} ", x);
    }
    println!();
}

fn main() {
    let v = vec![1, 2, 3];
    print_all(v.into_iter());

    let boxed: Box<dyn Iterator<Item = i32>> = Box::new(0..5);
    for x in boxed {
        print!("{} ", x);
    }
    println!();
}

输出:

1
2
1 2 3
0 1 2 3 4

impl Iterator<Item = i32> 和 Box<dyn Iterator<Item = i32>> 里的 Item = i32 都是关联类型约束:把这个 trait 的 Item 钉在 i32 上。0..5 是 Range<i32>,它实现的 Iterator 的 Item 正好是 i32,所以能装进这个 Box。如果换成 Box::new(vec!["a", "b"].into_iter()),Item 是 &str,就装不进去了——Box<dyn Iterator<Item = i32>> 只收产出 i32 的迭代器。

这里有个容易混淆的点:Item = i32 不是泛型参数,不能写成 Iterator<i32>。Iterator 没有泛型参数,Item 是它肚子里的关联类型,约束它只能用 Trait<Assoc = Type> 这种写法。多个关联类型就用逗号隔开,比如 dyn Graph<Node = usize, Edge = String>。

顺带一提,上一节提到的 Iterator 能做成 trait 对象、而 Clone 不能,靠的正是这条:Iterator 的方法都不返回 Self、没有泛型参数,满足对象安全;把 Item 定下来之后,虚表里的 next 就知道返回什么类型了。

泛型关联类型:给关联类型加一个生命周期参数

关联类型到这里还差最后一块拼图。看这个需求:写一个迭代器,它拥有一个 Vec<String>,每次 next 返回一个借用自这个 Vec 的 &str。直觉的写法是:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
struct WordIter {
    words: Vec<String>,
    pos: usize,
}

impl Iterator for WordIter {
    type Item = &str; // 编译失败:&str 借谁的?
    fn next(&mut self) -> Option<Self::Item> {
        let w = self.words.get(self.pos)?;
        self.pos += 1;
        Some(w)
    }
}

编译器报错:type Item = &str 里缺生命周期。问题不在 &str 本身,而在 Item 这个关联类型没有位置放生命周期:next(&mut self) 返回的引用借的是 self,可 Item 是在 impl 那一刻就定死的,它没法说“我的生命周期就是这次 next 调用时 &mut self 的那个生命周期”。普通 Iterator 的 Item 是个固定类型,而这里需要的 Item 是“跟着每次调用走”的。

这就是泛型关联类型(Generic Associated Type,GAT)要解决的问题:关联类型也可以带自己的泛型参数,最常见的是带一个生命周期参数。GAT 在 Rust 1.65 稳定,现在可以直接用。标准写法是先定义一个“借用迭代器” trait:

1
2
3
4
5
6
trait LendingIterator {
    type Item<'a>
    where
        Self: 'a;
    fn next(&mut self) -> Option<Self::Item<'_>>;
}

type Item<'a>:关联类型自己带了一个生命周期参数 'a。where Self: 'a 是必须写的限定:Item<'a> 里借的东西,至多只能活到 Self 活到的时间——借用不能比它借出的主人活得久。Self::Item<'_> 里的 '_ 是匿名生命周期,意思是“这次 next 调用时 &mut self 的那个生命周期”,编译器会按调用现场推导。

用它实现一个按块切分数据的迭代器:每次 next 返回一片借用自内部数据的切片:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
trait LendingIterator {
    type Item<'a>
    where
        Self: 'a;
    fn next(&mut self) -> Option<Self::Item<'_>>;
}

struct Chunks<'a> {
    data: &'a [i32],
    size: usize,
    pos: usize,
}

impl<'a> LendingIterator for Chunks<'a> {
    type Item<'b> = &'b [i32] where Self: 'b;

    fn next(&mut self) -> Option<Self::Item<'_>> {
        if self.pos >= self.data.len() {
            return None;
        }
        let end = (self.pos + self.size).min(self.data.len());
        let chunk = &self.data[self.pos..end];
        self.pos = end;
        Some(chunk)
    }
}

fn main() {
    let data = vec![1, 2, 3, 4, 5, 6, 7];
    let mut it = Chunks {
        data: &data,
        size: 3,
        pos: 0,
    };
    while let Some(chunk) = it.next() {
        println!("{:?}", chunk);
    }
}

输出:

1
2
3
[1, 2, 3]
[4, 5, 6]
[7]

实现里 type Item<'b> = &'b [i32] where Self: 'b; 是在说:对任意一个生命周期 'b(只要 Self 能活到 'b),这次 next 产出的就是一个活 'b 的切片。注意这个限定的位置:trait 定义里写在 type Item<'a> 后面,实现里写在 = 后面——写在 = 前面也能编译,但会触发一条 deprecation 警告。Chunks<'a> 的 data 是 &'a [i32],Self: 'b 保证了 'a 至少活到 'b,所以从 &'a [i32] 里切一片 &'b [i32] 出来是合法的。while let Some(chunk) = it.next() 每轮拿到的 chunk 只在当轮有效,下一轮 next 需要 &mut self,上一轮的借用必须先结束——这正是借用检查在起作用,GAT 没有绕过它,只是让类型系统能表达“我借出来的东西跟着这次调用走”。

GAT 最早就是为了这种“借用迭代器”才引入的:标准库的 Iterator 永远做不到这一点,因为它的 Item 没有生命周期参数。现实里的例子是 windows、chunks 这类返回切片的迭代器,以及一些数据库游标、解析器——它们产出的是借用自自身数据的视图,用 GAT 才能表达。

GAT 的使用边界要说清楚:GAT 本身只是“关联类型可以带参数”,参数不一定是生命周期,也可以是类型参数,但目前最成熟的用法就是生命周期参数;另外 GAT 和 dyn Trait 的配合目前还很受限,写 GAT 一般配合泛型用,不要指望把它装进 Box<dyn LendingIterator>。这一节知道它存在、会写最简单的形式就够了,后面讲到异步(第 17 章)时还会再见到它——异步里很多 trait 都用 GAT 来表达“返回的 future 借用了 self”。

常见坑

  • 实现里漏写 type Item = ...。impl Iterator for Counter 只写了 next 没写 Item,编译器报 not all trait items implemented, missing: Item。关联类型是 trait 的一部分,实现必须把它交齐。
  • trait 对象上不写关联类型。Box<dyn Iterator> 编译不过,报错会说关联类型 Item 的值必须指明。写成 Box<dyn Iterator<Item = i32>>,把 Item 钉死。
  • 把关联类型约束写成泛型参数。Iterator<i32> 是错的,Iterator 没有泛型参数;正确写法是 Iterator<Item = i32>。
  • 在 trait 定义里给关联类型写默认值。type Item = u32; 写在 trait 定义里,在稳定版 Rust 上编不过——关联类型默认值还是不稳定的特性,只能在实现里写 type Item = ...。
  • 以为关联类型能让一个类型对同一个 trait 有多种实现。一个类型对一个 trait 只能实现一次,所以 Item 只有一个值。想让同一个类型产出两种元素,要么换两个类型,要么用泛型参数。
  • GAT 定义里漏了 where Self: 'a。trait 定义里 type Item<'a>; 不带这个限定,编译器会报 missing required bound on Item。这个限定是 GAT 语法的一部分;实现里写成 type Item<'b> = &'b [i32] where Self: 'b;,限定放在 = 后面,放在 = 前面会触发 deprecation 警告。
  • 拿 GAT 去套 dyn。Box<dyn LendingIterator> 目前行不通,GAT trait 做 trait 对象受限很严重。需要动态分发时,先想想能不能用泛型,或者把 GAT 换成普通关联类型加拥有所有权的值。

动手练习

写一个栈:定义 trait Stack,带一个关联类型 Item 和 push、pop、peek 三个方法;再定义 VecStack<T>(内部包一个 Vec<T>)来实现它;最后在 main 里压入三个字符串,打印栈顶、弹出两个、再打印栈顶。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
trait Stack {
    type Item;
    fn push(&mut self, item: Self::Item);
    fn pop(&mut self) -> Option<Self::Item>;
    fn peek(&self) -> Option<&Self::Item>;
}

struct VecStack<T> {
    items: Vec<T>,
}

impl<T> Stack for VecStack<T> {
    type Item = T;

    fn push(&mut self, item: T) {
        self.items.push(item);
    }

    fn pop(&mut self) -> Option<T> {
        self.items.pop()
    }

    fn peek(&self) -> Option<&T> {
        self.items.last()
    }
}

fn main() {
    let mut s = VecStack { items: Vec::new() };
    s.push(String::from("第一"));
    s.push(String::from("第二"));
    s.push(String::from("第三"));
    println!("栈顶:{:?}", s.peek());
    println!("弹出:{:?}", s.pop());
    println!("弹出:{:?}", s.pop());
    println!("栈顶:{:?}", s.peek());
}
  1. 把 Stack 改成泛型参数版 trait Stack<T> { fn push(&mut self, item: T); fn pop(&mut self) -> Option<T>; fn peek(&self) -> Option<&T>; },再让 VecStack<T> 实现它。然后想想:调用方写 fn show(s: &impl Stack<String>) 和关联类型版的 fn show(s: &impl Stack<Item = String>),用起来有什么区别?“一个栈只有一种元素类型”这个事实,哪个写法表达得更直接?
  2. 给 Stack 的关联类型加一个约束 type Item: std::fmt::Debug;,再写一个 fn print_top<S: Stack>(s: &S),用 {:?} 打印栈顶元素。如果某个实现把 Item 定成一个没有实现 Debug 的类型,编译器会在哪一行报错?为什么?
  3. (GAT 小挑战)照着本节 Chunks 的样子,写一个 Windows 借用迭代器:内部存 &[i32] 和窗口大小,每次 next 返回一个长度为窗口大小的切片,窗口每次向后滑动 1。对 [1, 2, 3, 4, 5] 用窗口 3 跑一遍,输出应该是 [1, 2, 3]、[2, 3, 4]、[3, 4, 5]。再想想:窗口大小为 0 时 next 会发生什么?怎么防住?

小结与预告

核心就四句话:关联类型是 trait 里留给实现者定的类型,type Item; 声明、type Item = u32; 交卷;一个类型对一个 trait 只能实现一次,所以关联类型只有一个值——实现者说了算、调用方没得选的,就用关联类型;trait 对象里必须把关联类型钉死,写 Box<dyn Iterator<Item = i32>>;普通关联类型放不下生命周期,需要“借出来的东西跟着这次调用走”时,用 GAT(type Item<'a> where Self: 'a;),Rust 1.65 起稳定可用。

下一节 12.1:闭包:捕获与 Fn trait。闭包是 Rust 里最常用的匿名函数——它怎么捕获周围的变量,Fn、FnMut、FnOnce 三个 trait 又有什么区别,什么时候该用闭包、什么时候该写普通函数,下节接着讲。


配套练习:在学习站动手练这一节

本文代码基于 Rust 1.8x / Edition 2024 验证。

JerryHome · 记录技术与生活