默认方法与 trait 作为参数

学习目标

读完这一节,你会给 trait 的方法写默认实现,知道实现者什么时候直接用默认、什么时候覆盖它;理解默认方法之间可以互相调用;还会用 impl Trait 把 trait 当作函数参数,让一个函数接受“任何实现了这个 trait 的类型”。

上一节练习答案

上一节的练习是给电影和歌曲定义 Describable,给电影派生 Debug、Clone、PartialEq 并手写 Display,以及为 String 实现自己的 Shout 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
use std::fmt;

trait Describable {
    fn describe(&self) -> String;
}

#[derive(Debug, Clone, PartialEq)]
struct Movie {
    title: String,
    year: u32,
    rating: f32,
}

struct Song {
    title: String,
    artist: String,
    duration_secs: u32,
}

impl Describable for Movie {
    fn describe(&self) -> String {
        format!("电影《{}》({} 年),评分 {:.1}", self.title, self.year, self.rating)
    }
}

impl Describable for Song {
    fn describe(&self) -> String {
        format!(
            "歌曲《{}》,歌手 {},时长 {} 分 {} 秒",
            self.title, self.artist, self.duration_secs / 60, self.duration_secs % 60
        )
    }
}

impl fmt::Display for Movie {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "《{}》({},评分:{:.1})", self.title, self.year, self.rating)
    }
}

trait Shout {
    fn shout(&self) -> String;
}

impl Shout for String {
    fn shout(&self) -> String {
        format!("{}!", self.to_uppercase())
    }
}

fn main() {
    let m1 = Movie {
        title: String::from("星际穿越"),
        year: 2014,
        rating: 9.3,
    };
    let m2 = m1.clone();
    println!("{}", m1.describe());
    println!("Display:{}", m1);
    println!("克隆后相等吗:{}", m1 == m2);

    let s = Song {
        title: String::from("夜曲"),
        artist: String::from("周杰伦"),
        duration_secs: 240,
    };
    println!("{}", s.describe());

    let word = String::from("hello");
    println!("{}", word.shout());
}

运行结果:

1
2
3
4
5
电影《星际穿越》(2014 年),评分 9.3
Display:《星际穿越》(2014,评分:9.3)
克隆后相等吗:true
歌曲《夜曲》,歌手 周杰伦,时长 4 分 0 秒
HELLO!

要点:describe 的格式由每个类型自己定,电影和歌曲的描述完全不同,但调用方式一模一样——这正是 trait 的用处。Display 的手写实现用了 {:.1},把评分保留一位小数;PartialEq 派生出来的 == 是逐字段比较,克隆出来的副本和原值相等。shout 里用了 to_uppercase(),中文没有大小写所以原样输出,只多了感叹号;英文 "hello" 变成了 "HELLO!"。第三题的第二部分是故意写错的:Display 是标准库的 trait,Vec<i32> 也是标准库的类型,两者都不是本地的,孤儿规则直接拒绝:

1
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types

第四题的回答:trait 的方法是一组约定,类型实现 trait 等于承诺“能做这些事”,调用者按 trait 来用,不关心具体类型;普通 impl 块的方法只属于这一个类型,别的类型调不了。#[derive(Debug)] 和手写 impl Debug 效果一样,派生只是编译器按固定套路帮你生成了同样的代码。Display 不能派生,因为编译器不知道你想把值打印成什么样子,格式只能由你定。孤儿规则要求 trait 和类型至少一个是本地的,是为了防止两个 crate 给同一个类型实现同一个 trait,让编译器无所适从。

核心概念

默认方法:trait 自带实现

上一节的 trait 方法都只有签名、没有方法体,实现者必须一个一个写出来。但有些方法,大多数类型的实现都一模一样——每个类型都手写一遍是重复劳动。Rust 允许在定义 trait 时直接给方法写上方法体,这就叫默认方法(default method)。

有了默认实现,实现这个 trait 的类型可以不写这个方法,直接用默认的;如果默认的不合用,也可以自己写一个覆盖它:

1
2
3
4
5
6
7
8
trait Summary {
    fn summarize_author(&self) -> String;

    // 默认方法:大多数类型直接用它就够了
    fn summarize(&self) -> String {
        format!("(阅读更多:{})", self.summarize_author())
    }
}

默认方法适合放“大多数实现都一样”的行为。summarize_author 每个类型都不同,必须是必需方法;但“在摘要后面加一个阅读提示”这个行为,所有类型的做法都一样,就适合写成默认方法。实现者只写真正不同的部分,公共逻辑由 trait 一次写好。

默认方法可以调用 trait 里的其他方法

默认方法还可以调用同一个 trait 里的其他方法。于是 trait 可以只要求实现者提供一两个“核心方法”,其余方法都由默认实现从核心方法推导出来。这是一种很常见的设计:核心方法小而必需,派生方法多而方便。

比如一个 Animal trait,核心方法只有一个 name,返回动物的名字;sound 和 introduce 都是默认方法,introduce 内部调用 name 和 sound 拼出自我介绍。狗的叫声特殊,就覆盖 sound;猫没有特殊叫声,什么都不写,只实现 name 就够了。

注意一个限制:覆盖默认方法之后,调不到被覆盖掉的默认实现——Rust 没有“调用父类默认实现”的写法。如果覆盖后还想用默认的逻辑,只能把那部分逻辑抽成另一个方法,让默认实现和覆盖实现都调它。

trait 作为参数:impl Trait

trait 不只能定义在类型上,还能直接出现在函数参数里。写 fn notify(item: &impl Summary),意思是:参数 item 可以是任何类型,只要它实现了 Summary。新闻也好,推文也好,只要实现了 Summary,都能传给同一个 notify。

这正是上一节埋下的伏笔:trait 把“能做什么”抽成约定之后,函数就不用关心参数具体是什么类型,只关心它会什么。调用者传什么类型都可以,编译器在编译时为每种实际类型生成对应的代码,运行时没有任何额外开销。

&impl Summary 里的 & 也值得注意:参数是借用,函数只读数据,不拿走所有权。如果写成 fn notify(item: impl Summary),那就是按值传入,调用后所有权就转移了。大多数情况下,通知、打印这类函数用借用就够了。

impl Trait 其实是泛型的简写

fn notify(item: &impl Summary) 和 fn notify<T: Summary>(item: &T) 是一回事,后者是第 8 章学过的泛型加 trait bound 的写法,impl Trait 只是它的简写。两种写法编译出来的代码完全一样,选哪个主要看可读性:参数只有一个 trait bound 时,impl Trait 更短;bound 复杂时,泛型加 where 子句更清楚。

两种写法有一个细微的区别:两个 impl Trait 参数彼此独立,可以是不同类型;泛型用同一个类型参数 T 时,两个参数必须是同一类型。想让函数接受两个不同的 Summary,写 fn f(a: &impl Summary, b: &impl Summary);想强制两个参数是同一类型,写泛型 fn f<T: Summary>(a: &T, b: &T)。

多个 trait bound:用 + 组合

一个参数想同时满足多个 trait,用 + 把它们连起来:&(impl Summary + Display) 要求参数既实现了 Summary,又实现了 Display。函数里既能调 summarize,又能用 {} 打印。+ 后面可以继续加,impl A + B + C 就是同时实现三个 trait。

可运行代码

第一个程序:Summary 的默认方法。summarize_author 是必需方法,summarize 是默认方法:

 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
trait Summary {
    fn summarize_author(&self) -> String;

    fn summarize(&self) -> String {
        format!("(阅读更多:{})", self.summarize_author())
    }
}

struct NewsArticle {
    headline: String,
    author: String,
}

struct Tweet {
    username: String,
    content: String,
}

impl Summary for NewsArticle {
    fn summarize_author(&self) -> String {
        format!("{},作者 {}", self.headline, self.author)
    }

    // 覆盖默认方法:新闻的摘要有自己的格式
    fn summarize(&self) -> String {
        format!("{} —— {}", self.headline, self.author)
    }
}

impl Summary for Tweet {
    fn summarize_author(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
    // Tweet 没有写 summarize,直接用默认实现
}

fn main() {
    let article = NewsArticle {
        headline: String::from("Rust 1.85 发布"),
        author: String::from("小优"),
    };
    let tweet = Tweet {
        username: String::from("rustacean"),
        content: String::from("今天学了 trait!"),
    };
    println!("{}", article.summarize());
    println!("{}", tweet.summarize());
}

运行结果:

1
2
Rust 1.85 发布 —— 小优
(阅读更多:rustacean: 今天学了 trait!)

新闻覆盖了默认的 summarize,用了自己的格式;推文没有写 summarize,直接用了默认实现——默认实现内部调用了推文自己实现的 summarize_author,所以输出里还是推文的内容。默认方法不是“写死”的行为,它可以调用实现者提供的方法。

第二个程序:Animal trait,核心方法 name,默认方法 sound 和 introduce:

 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
trait Animal {
    fn name(&self) -> &str;

    fn sound(&self) -> &str {
        "叫了一声"
    }

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

struct Dog {
    name: String,
}

struct Cat {
    name: String,
}

impl Animal for Dog {
    fn name(&self) -> &str {
        &self.name
    }

    fn sound(&self) -> &str {
        "汪汪"
    }
}

impl Animal for Cat {
    fn name(&self) -> &str {
        &self.name
    }
    // Cat 只实现 name,sound 和 introduce 全是默认实现
}

fn main() {
    let dog = Dog {
        name: String::from("阿黄"),
    };
    let cat = Cat {
        name: String::from("咪咪"),
    };
    println!("{}", dog.introduce());
    println!("{}", cat.introduce());
}

运行结果:

1
2
我是阿黄,汪汪。
我是咪咪,叫了一声。

狗覆盖了 sound,猫什么都没覆盖:Cat 的 impl 块里只有一个 name,sound 和 introduce 全是默认实现。注意 introduce 是默认方法,但它调用了实现者提供的 name——默认方法可以依赖必需方法,这就是“核心方法 + 派生方法”的设计。

第三个程序:impl Trait 作参数,一个 notify 函数接受任何实现了 Summary 的类型:

 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
trait Summary {
    fn summarize(&self) -> String;
}

struct NewsArticle {
    headline: String,
    author: String,
}

struct Tweet {
    username: String,
    content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{},作者 {}", self.headline, self.author)
    }
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

fn notify(item: &impl Summary) {
    println!("新内容:{}", item.summarize());
}

fn main() {
    let article = NewsArticle {
        headline: String::from("Rust 1.85 发布"),
        author: String::from("小优"),
    };
    let tweet = Tweet {
        username: String::from("rustacean"),
        content: String::from("今天学了 trait!"),
    };
    notify(&article);
    notify(&tweet);
}

运行结果:

1
2
新内容:Rust 1.85 发布,作者 小优
新内容:rustacean: 今天学了 trait!

同一个 notify,传新闻和传推文都能工作。函数签名里只写了“实现了 Summary”,没有提任何具体类型——这就是 trait 作为参数的威力:写一次函数,所有实现这个 trait 的类型都能用。

第四个程序:多个 trait bound 和泛型的同一类型约束:

 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
use std::fmt::{self, Display};

trait Summary {
    fn summarize(&self) -> String;
}

struct Book {
    title: String,
    pages: u32,
}

impl Summary for Book {
    fn summarize(&self) -> String {
        format!("《{}》({} 页)", self.title, self.pages)
    }
}

impl fmt::Display for Book {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "《{}》({} 页)", self.title, self.pages)
    }
}

// 要求同时实现 Summary 和 Display
fn print_both(item: &(impl Summary + Display)) {
    println!("Display:{}", item);
    println!("Summary:{}", item.summarize());
}

// 两个参数必须是同一类型
fn same_type<T: Summary>(a: &T, b: &T) {
    println!("第一本:{}", a.summarize());
    println!("第二本:{}", b.summarize());
}

fn main() {
    let b1 = Book {
        title: String::from("Rust 程序设计语言"),
        pages: 560,
    };
    let b2 = Book {
        title: String::from("Rust Cookbook"),
        pages: 320,
    };
    print_both(&b1);
    same_type(&b1, &b2);
}

运行结果:

1
2
3
4
Display:《Rust 程序设计语言》(560 页)
Summary:《Rust 程序设计语言》(560 页)
第一本:《Rust 程序设计语言》(560 页)
第二本:《Rust Cookbook》(320 页)

print_both 的参数是 &(impl Summary + Display),函数里既用了 {} 打印(需要 Display),又调了 summarize(需要 Summary),两个 bound 缺一不可。same_type 是泛型写法,T 要求两个参数是同一类型——这里传了两本 Book,没问题;如果一个传 Book、一个传别的类型,编译器会报错。想接受两个不同类型,就用两个 impl Trait 参数:

1
2
3
4
fn two_items(a: &impl Summary, b: &impl Summary) {
    println!("{}", a.summarize());
    println!("{}", b.summarize());
}

常见坑

  • 覆盖默认方法后调不到默认实现:Rust 没有 super 的写法。覆盖之前先想清楚:是完全替换,还是只想在默认行为上加一点?后者要把公共逻辑抽成另一个方法,让默认实现和覆盖实现都调它。
  • 默认方法不是“可写可不写”的摆设:实现者漏写一个必需方法会编译失败,但漏写默认方法不会——它悄悄用了默认实现。如果默认行为不符合你的类型,bug 藏得很深。给类型实现 trait 时,把默认方法逐个过一遍。
  • impl Trait 参数彼此独立:fn f(a: &impl Summary, b: &impl Summary) 的两个参数可以是不同类型。想强制同一类型,用泛型 fn f<T: Summary>(a: &T, b: &T)。
  • impl Summary 和 &impl Summary 别混了:前者按值传入,拿走所有权;后者借用,只读。通知、打印这类函数一般用借用。
  • 默认方法里调的方法必须是 trait 的方法:默认方法只能调用同一个 trait 里声明的方法,不能调类型自己的 impl 块里的方法——trait 定义时还不知道实现者是谁。

动手练习

  1. 给 9.1 节的 Shape trait 加一个默认方法 describe(&self) -> String,用 area 和 perimeter 拼出描述(如 "面积 20.00,周长 18.00");Circle 覆盖它,加上“圆形”前缀,Rectangle 直接用默认实现。在 main 里分别调用验证。
  2. 定义 trait Speaker:必需方法 fn name(&self) -> &str,默认方法 fn introduce(&self) -> String 返回 "我是 X";定义 Teacher { name: String, subject: String } 和 Student { name: String, grade: u32 },分别为它们实现 Speaker,Teacher 覆盖 introduce,加上所教科目,Student 用默认实现。
  3. 写函数 fn greet_all(a: &impl Speaker, b: &impl Speaker),打印两人的自我介绍;再写泛型版 fn greet_pair<T: Speaker>(a: &T, b: &T);先传两个 Teacher 调用 greet_pair,再试着传一个 Teacher 和一个 Student,看编译器报什么错,理解两种写法的区别。
  4. 回答:默认方法有什么好处?什么时候该覆盖默认方法?impl Trait 参数和泛型参数有什么区别?fn f(x: impl Summary) 和 fn f(x: &impl Summary) 的区别是什么?

小结与预告

核心就两句话:trait 的方法可以带默认实现,实现者不用就直接用默认的,不合用就覆盖;impl Trait 可以把 trait 当作函数参数,让函数接受任何实现了这个 trait 的类型,它是泛型 trait bound 的简写,多个 bound 用 + 组合。

下一节 9.3:Trait Bound 与 where 子句——bound 写多了怎么组织,where 子句怎么让复杂签名变清楚。


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

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

JerryHome · 记录技术与生活