Trait Bound 与 where 子句

学习目标

读完这一节,你会给泛型参数写 trait bound,用 where 子句把写多了的 bound 从尖括号里搬出来,让签名重新变清楚,还会写“条件方法”——只有类型满足 bound 时才有的方法。

上一节练习答案

上一节的练习是给 9.1 节的 Shape trait 加默认方法、定义 Speaker trait、对比 impl Trait 参数和泛型参数。参考答案:

  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
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
trait Shape {
    fn area(&self) -> f64;
    fn perimeter(&self) -> f64;

    fn describe(&self) -> String {
        format!("面积 {:.2},周长 {:.2}", self.area(), self.perimeter())
    }
}

struct Circle {
    radius: f64,
}

struct Rectangle {
    width: f64,
    height: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.radius * self.radius
    }

    fn perimeter(&self) -> f64 {
        2.0 * std::f64::consts::PI * self.radius
    }

    // 覆盖默认方法,加上“圆形”前缀
    fn describe(&self) -> String {
        format!("圆形:面积 {:.2},周长 {:.2}", self.area(), self.perimeter())
    }
}

impl Shape for Rectangle {
    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn perimeter(&self) -> f64 {
        2.0 * (self.width + self.height)
    }
    // 直接用默认的 describe
}

// 练习 2:Speaker trait
trait Speaker {
    fn name(&self) -> &str;

    fn introduce(&self) -> String {
        format!("我是 {}", self.name())
    }
}

struct Teacher {
    name: String,
    subject: String,
}

struct Student {
    name: String,
    grade: u32,
}

impl Speaker for Teacher {
    fn name(&self) -> &str {
        &self.name
    }

    fn introduce(&self) -> String {
        format!("我是 {},教 {}", self.name, self.subject)
    }
}

impl Speaker for Student {
    fn name(&self) -> &str {
        &self.name
    }
    // 用默认的 introduce
}

// 练习 3:impl Trait 参数与泛型参数
fn greet_all(a: &impl Speaker, b: &impl Speaker) {
    println!("{}", a.introduce());
    println!("{}", b.introduce());
}

fn greet_pair<T: Speaker>(a: &T, b: &T) {
    println!("{}", a.introduce());
    println!("{}", b.introduce());
}

fn main() {
    let c = Circle { radius: 5.0 };
    let r = Rectangle {
        width: 4.0,
        height: 5.0,
    };
    println!("{}", c.describe());
    println!("{}", r.describe());

    let t1 = Teacher {
        name: String::from("王老师"),
        subject: String::from("数学"),
    };
    let t2 = Teacher {
        name: String::from("李老师"),
        subject: String::from("语文"),
    };
    let s = Student {
        name: String::from("小明"),
        grade: 7 };

    greet_all(&t1, &s); // 两个不同类型,可以
    greet_pair(&t1, &t2); // 两个 Teacher,可以
    println!("{} 在读 {} 年级", s.name, s.grade);
    // greet_pair(&t1, &s); // 编译失败:T 不能同时是 Teacher 和 Student
}

运行结果:

1
2
3
4
5
6
7
圆形:面积 78.54,周长 31.42
面积 20.00,周长 18.00
我是 王老师,教 数学
我是 小明
我是 王老师,教 数学
我是 李老师,教 语文
小明 在读 7 年级

要点:Circle 覆盖了 describe,Rectangle 用默认实现——默认方法内部调了 area 和 perimeter 这两个必需方法。Teacher 覆盖了 introduce,Student 用默认实现。greet_all 的两个参数是独立的 impl Trait,可以是不同类型;greet_pair 共用一个类型参数 T,混传 Teacher 和 Student 会报错:

1
2
3
4
5
error[E0308]: mismatched types
   --> main.rs:116:21
    |
116 |     greet_pair(&t1, &s);
    |     ----------      ^^ expected `&Teacher`, found `&Student`

第四题的回答:默认方法把“大多数实现都一样”的逻辑只写一次,不合用就覆盖。impl Trait 参数是泛型的简写,但两个 impl Trait 参数彼此独立;泛型参数能强制多个参数是同一类型,也能把同一个类型参数用在返回值等位置。fn f(x: impl Summary) 按值传入,拿走所有权;fn f(x: &impl Summary) 只借用。

核心概念

Trait bound:给泛型提要求

第 8 章的 fn largest<T: PartialOrd>(list: &[T]) -> &T 里,冒号后面的 PartialOrd 就是 trait bound:调用者传进来的类型 T 必须实现 PartialOrd,否则编译都过不了。Bound 是编译器在编译时检查的“入场券”:类型不符合,函数根本不存在;符合了,函数体里就能放心地调这个 trait 的方法。没有 bound 的 T,函数里除了移动、借用,几乎什么都干不了。

Bound 多了,签名就读不懂了

一个 bound 还好,两个、三个叠上去签名就开始变长:

1
2
3
fn print_and_compare<T: Display + PartialOrd + Copy>(a: T, b: T) {
    // ...
}

再加一个泛型参数 U,又要各自带 bound:

1
2
3
fn report<T: Display + Clone, U: Debug + PartialEq>(first: T, second: U) {
    // ...
}

这时候函数名和参数被埋在一堆 bound 中间,读签名得先跳过尖括号——调用者想知道的是“这个函数接受什么、返回什么”,bound 只是实现细节,不该挡在最前面。

where 子句:把 bound 搬到签名后面

where 子句就是为了解决这个问题:尖括号里只留类型参数的名字,bound 全部移到函数签名的后面、函数体的前面:

1
2
3
4
5
6
fn print_and_compare<T>(a: T, b: T)
where
    T: Display + PartialOrd + Copy,
{
    // ...
}

两种写法意思完全一样,区别只在可读性:第一行一眼看清函数接受什么、返回什么,bound 在下面一行一行列清楚,再多也不挤。多个泛型参数时更明显:

1
2
3
4
5
6
7
fn report<T, U>(first: T, second: U)
where
    T: Display + Clone,
    U: Debug + PartialEq,
{
    // ...
}

每个类型参数的 bound 各占一行,加减都只动一行。where 子句的位置固定:返回值之后、函数体之前;没有返回值时跟在参数列表后面。

条件方法:只有满足 bound 才有的方法

where 子句也能用在 impl 块上:impl<T> Pair<T> where T: Display + PartialOrd 的意思是,这个 impl 块里的方法,只有 T 同时实现 Display 和 PartialOrd 时才存在;T 不满足条件,Pair 照样能创建、能用别的方法,只是不存在这个方法。

bound 写在结构体定义上,之后每个 impl 块都要把同样的 bound 再写一遍,哪怕那个方法根本用不到 Display。习惯是:bound 写在需要它的方法或 impl 块上,不写在类型定义上。

where 与直接写 bound 完全等价

where 子句只是换个写法,不改变任何语义:fn f<T: Display>(x: T) 和 fn f<T>(x: T) where T: Display 是同一个函数。选哪个只看可读性:bound 少、签名短时直接写尖括号里;bound 多、类型参数多时用 where 子句。

可运行代码

第一个程序:同一个函数,两种写法,行为完全一样:

 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
use std::fmt::Display;

fn show_max_inline<T: Display + PartialOrd + Copy>(a: T, b: T) {
    if a >= b {
        println!("较大的是:{}", a);
    } else {
        println!("较大的是:{}", b);
    }
}

fn show_max_where<T>(a: T, b: T)
where
    T: Display + PartialOrd + Copy,
{
    if a >= b {
        println!("较大的是:{}", a);
    } else {
        println!("较大的是:{}", b);
    }
}

fn main() {
    show_max_inline(3, 7);
    show_max_inline("苹果", "香蕉");
    show_max_where(3, 7);
    show_max_where("苹果", "香蕉");
}

运行结果:

1
2
3
4
较大的是:7
较大的是:香蕉
较大的是:7
较大的是:香蕉

三个 bound 各有分工:Display 管打印,PartialOrd 管比较,Copy 让按值传入的 a、b 还能在 println! 里再用。缺一个,编译器就会在用到的地方报错。

第二个程序:Pair<T> 的条件方法。new 没有 bound,任何类型都能创建 Pair;cmp_display 写在带 where 子句的 impl 块里,只有 T 同时实现 Display 和 PartialOrd 时才存在:

 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
40
41
use std::fmt::Display;

struct Pair<T> {
    x: T,
    y: T,
}

impl<T> Pair<T> {
    fn new(x: T, y: T) -> Self {
        Self { x, y }
    }
}

impl<T> Pair<T>
where
    T: Display + PartialOrd,
{
    fn cmp_display(&self) {
        if self.x >= self.y {
            println!("较大的成员是 x = {}", self.x);
        } else {
            println!("较大的成员是 y = {}", self.y);
        }
    }
}

struct Noisy {
    level: u32,
}

fn main() {
    let p1 = Pair::new(10, 20);
    p1.cmp_display();

    let p2 = Pair::new(String::from("hello"), String::from("world"));
    p2.cmp_display();

    let p3 = Pair::new(Noisy { level: 5 }, Noisy { level: 9 });
    // p3.cmp_display(); // 编译失败:Noisy 没有实现 Display
    println!("p3 也能创建:level = {}", p3.x.level);
}

运行结果:

1
2
3
较大的成员是 y = 20
较大的成员是 y = world
p3 也能创建:level = 5

i32 和 String 都实现了 Display 和 PartialOrd,Pair<i32> 和 Pair<String> 都能调 cmp_display;Noisy 没有实现 Display,Pair<Noisy> 能创建,但调 cmp_display 就会编译失败:

1
2
3
4
5
error[E0599]: the method `cmp_display` exists for struct `Pair<Noisy>`, but its trait bounds were not satisfied
  --> main.rs:39:8
   |
39 |     p3.cmp_display();
   |        ^^^^^^^^^^^ method cannot be called on `Pair<Noisy>` due to unsatisfied trait bounds

第三个程序:两个泛型参数,inline 写法和 where 写法并排对比:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use std::fmt::{Debug, Display};

fn report_inline<T: Display + Clone, U: Debug>(first: T, second: U) {
    let copy = first.clone();
    println!("inline 写法:{}(副本:{}),{:?}", first, copy, second);
}

fn report<T, U>(first: T, second: U)
where
    T: Display + Clone,
    U: Debug,
{
    let copy = first.clone();
    println!("where 写法:{}(副本:{}),{:?}", first, copy, second);
}

fn main() {
    report_inline(String::from("Rust"), vec![1, 2, 3]);
    report(String::from("Rust"), vec![1, 2, 3]);
}

运行结果:

1
2
inline 写法:Rust(副本:Rust),[1, 2, 3]
where 写法:Rust(副本:Rust),[1, 2, 3]

T 需要 Clone,是因为 first.clone() 之后还要再打印 first;U 只用 {:?} 打印,所以只要 Debug。

第四个程序:方法级的 where 子句。Bag<T> 的 new 和 push 不需要 bound,任何类型都能装;只有 print_all 需要 Display:

 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
use std::fmt::Display;

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

impl<T> Bag<T> {
    fn new() -> Self {
        Self { items: Vec::new() }
    }

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

    fn print_all(&self)
    where
        T: Display,
    {
        for item in &self.items {
            println!("- {}", item);
        }
    }
}

fn main() {
    let mut bag = Bag::new();
    bag.push(1);
    bag.push(2);
    bag.push(3);
    bag.print_all();
    println!("袋子里有 {} 件东西", bag.items.len());
}

运行结果:

1
2
3
4
- 1
- 2
- 3
袋子里有 3 件东西

把 bound 精确地放在需要它的方法上,是 where 子句最常见的用法:类型本身保持通用,只有用到某个能力的方法才提要求。标准库也是这么做的:Vec<T> 本身没有 bound,sort 才要求 T: Ord。

常见坑

  • where 子句的位置:必须写在返回值之后、函数体之前,写在参数列表和返回值之间会报错。
  • 尖括号里的类型参数不能省:where 子句只补充 bound,不声明类型参数,T 必须先在 <> 里出现。
  • 结构体定义上写 bound 会“传染”:写了 struct Label<T: Display>,之后每个 impl 块都要把 T: Display 再写一遍,哪怕那个方法根本不用 Display。
  • 漏写 bound 的报错指向调用处:函数体里调了 a.summarize(),却忘了给 T 加 Summary bound,编译器报的是“找不到方法”——先检查 bound。
  • where 子句里每行一个 bound 时,行尾逗号别漏:bound 之间用逗号分隔,最后一项的逗号可省,中间的不能少。
  • 不要为了用 where 而用 where:bound 只有一个、签名本来就短时,直接写尖括号里更省事。

动手练习

  1. 把 9.2 节的 print_both 和 same_type 改写成 where 子句的写法,验证行为一致;再给 print_both 加一个 Debug bound,分别用 inline 和 where 两种写法加上,比较哪种更清楚。
  2. 给第二个程序的 Pair<T> 再加一个条件方法 largest(&self) -> &T,返回较大的那个成员的引用(只需要 PartialOrd),用带 where 子句的 impl 块写;用 Pair<i32> 和 Pair<String> 验证;再去掉 PartialOrd bound,看编译器报什么错。
  3. 定义泛型结构体 Shelf<T> { books: Vec<T> },new 和 push 不需要 bound;再写方法 print_titles,要求 T: Display,用方法级的 where 子句;然后把 T: Display 写到结构体定义上,观察 impl 块的变化。
  4. 回答:where 子句和直接写在尖括号里的 bound 有什么区别?把 bound 写在结构体定义上有什么坏处?

小结与预告

核心就两句话:trait bound 是给泛型参数提的要求,写在尖括号里或 where 子句里意思完全一样;bound 多了就用 where 子句搬到签名后面,一个类型参数的 bound 占一行,impl 块和方法上的 where 还能做出“条件方法”。

下一节 10.1:为什么需要生命周期——引用能活多久的问题躲不掉了。


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

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

JerryHome · 记录技术与生活