Traits

特征 Trait 可以告诉编译器一个特定的类型所具有的、且能跟其它类型共享的特性。我们可以使用特征通过抽象的方式来定义这种共享行为,还可以使用特征约束来限定一个泛型类型必须要具有某个特定的行为。

Note: 特征跟其它语言的接口较为类似,但是仍然有一些区别

示例

2. struct Sheep { naked: bool, name: String }

4. impl Sheep {
5. fn is_naked(&self) -> bool {
6. self.naked
7. }

9. fn shear(&mut self) {
10. if self.is_naked() {
11. // `Sheep` 结构体上定义的方法可以调用 `Sheep` 所实现的特征的方法
12. println!("{} is already naked...", self.name());
13. } else {
14. println!("{} gets a haircut!", self.name);

16. self.naked = true;
17. }
18. }
19. }

21. trait Animal {
22. // 关联函数签名;`Self` 指代实现者的类型
23. // 例如我们在为 Pig 类型实现特征时,那 `new` 函数就会返回一个 `Pig` 类型的实例,这里的 `Self` 指代的就是 `Pig` 类型
24. fn new(name: String) -> Self;

26. // 方法签名
27. fn name(&self) -> String;

29. fn noise(&self) -> String;

31. // 方法还能提供默认的定义实现
32. fn talk(&self) {
33. println!("{} says {}", self.name(), self.noise());
34. }
35. }

37. impl Animal for Sheep {
38. // `Self` 被替换成具体的实现者类型: `Sheep`
39. fn new(name: String) -> Sheep {
40. Sheep { name: name, naked: false }
41. }

43. fn name(&self) -> String {
44. self.name.clone()
45. }

47. fn noise(&self) -> String {
48. if self.is_naked() {
49. "baaaaah?".to_string()
50. } else {
51. "baaaaah!".to_string()
52. }
53. }

55. // 默认的特征方法可以被重写
56. fn talk(&self) {
57. println!("{} pauses briefly... {}", self.name, self.noise());
58. }
59. }

61. fn main() {
62. // 这里的类型注释时必须的
63. let mut dolly: Sheep = Animal::new("Dolly".to_string());
64. // TODO ^ 尝试去除类型注释,看看会发生什么

66. dolly.talk();
67. dolly.shear();
68. dolly.talk();
69. }

Exercises

  1. 🌟🌟
2. // 完成两个 `impl` 语句块
3. // 不要修改 `main` 中的代码
4. trait Hello {
5. fn say_hi(&self) -> String {
6. String::from("hi")
7. }

9. fn say_something(&self) -> String;
10. }

12. struct Student {}
13. impl Hello for Student {
14. }
15. struct Teacher {}
16. impl Hello for Teacher {
17. }

19. fn main() {
20. let s = Student {};
21. assert_eq!(s.say_hi(), "hi");
22. assert_eq!(s.say_something(), "I'm a good student");

24. let t = Teacher {};
25. assert_eq!(t.say_hi(), "Hi, I'm your new teacher");
26. assert_eq!(t.say_something(), "I'm not a bad teacher");

28. println!("Success!")
29. }

Derive 派生

我们可以使用 #[derive] 属性来派生一些特征,对于这些特征编译器会自动进行默认实现,对于日常代码开发而言,这是非常方便的,例如大家经常用到的 Debug 特征,就是直接通过派生来获取默认实现,而无需我们手动去完成这个工作。

想要查看更多信息,可以访问这里。

  1. 🌟🌟
2. // `Centimeters`, 一个元组结构体,可以被比较大小
3. #[derive(PartialEq, PartialOrd)]
4. struct Centimeters(f64);

6. // `Inches`, 一个元组结构体可以被打印
7. #[derive(Debug)]
8. struct Inches(i32);

10. impl Inches {
11. fn to_centimeters(&self) -> Centimeters {
12. let &Inches(inches) = self;

14. Centimeters(inches as f64 * 2.54)
15. }
16. }

18. // 添加一些属性让代码工作
19. // 不要修改其它代码!
20. struct Seconds(i32);

22. fn main() {
23. let _one_second = Seconds(1);

25. println!("One second looks like: {:?}", _one_second);
26. let _this_is_true = _one_second == _one_second;
27. let _this_is_false = _one_second > _one_second;

29. let foot = Inches(12);

31. println!("One foot equals {:?}", foot);

33. let meter = Centimeters(100.0);

35. let cmp =
36. if foot.to_centimeters() < meter {
37. "smaller"
38. } else {
39. "bigger"
40. };

42. println!("One foot is {} than one meter.", cmp);
43. }

运算符

在 Rust 中,许多运算符都可以被重载,事实上,运算符仅仅是特征方法调用的语法糖。例如 a + b 中的 + 是 std::ops::Add 特征的 add 方法调用,因此我们可以为自定义类型实现该特征来支持该类型的加法运算。

  1. 🌟🌟
2. use std::ops;

4. // 实现 fn multiply 方法
5. // 如上所述,`+` 需要 `T` 类型实现 `std::ops::Add` 特征
6. // 那么, `*` 运算符需要实现什么特征呢? 你可以在这里找到答案: https://doc.rust-lang.org/core/ops/
7. fn multiply

9. fn main() {
10. assert_eq!(6, multiply(2u8, 3u8));
11. assert_eq!(5.0, multiply(1.0, 5.0));

13. println!("Success!")
14. }
  1. 🌟🌟🌟
2. // 修复错误,不要修改 `main` 中的代码!
3. use std::ops;

5. struct Foo;
6. struct Bar;

8. struct FooBar;

10. struct BarFoo;

12. // 下面的代码实现了自定义类型的相加: Foo + Bar = FooBar
13. impl ops::Add<Bar> for Foo {
14. type Output = FooBar;

16. fn add(self, _rhs: Bar) -> FooBar {
17. FooBar
18. }
19. }

21. impl ops::Sub<Foo> for Bar {
22. type Output = BarFoo;

24. fn sub(self, _rhs: Foo) -> BarFoo {
25. BarFoo
26. }
27. }

29. fn main() {
30. // 不要修改下面代码
31. // 你需要为 FooBar 派生一些特征来让代码工作
32. assert_eq!(Foo + Bar, FooBar);
33. assert_eq!(Foo - Bar, BarFoo);

35. println!("Success!")
36. }

使用特征作为函数参数

除了使用具体类型来作为函数参数,我们还能通过 impl Trait 的方式来指定实现了该特征的参数:该参数能接受的类型必须要实现指定的特征。

  1. 🌟🌟🌟
2. // 实现 `fn summary`
3. // 修复错误且不要移除任何代码行
4. trait Summary {
5. fn summarize(&self) -> String;
6. }

8. #[derive(Debug)]
9. struct Post {
10. title: String,
11. author: String,
12. content: String,
13. }

15. impl Summary for Post {
16. fn summarize(&self) -> String {
17. format!("The author of post {} is {}", self.title, self.author)
18. }
19. }

21. #[derive(Debug)]
22. struct Weibo {
23. username: String,
24. content: String,
25. }

27. impl Summary for Weibo {
28. fn summarize(&self) -> String {
29. format!("{} published a weibo {}", self.username, self.content)
30. }
31. }

33. fn main() {
34. let post = Post {
35. title: "Popular Rust".to_string(),
36. author: "Sunface".to_string(),
37. content: "Rust is awesome!".to_string(),
38. };
39. let weibo = Weibo {
40. username: "sunface".to_string(),
41. content: "Weibo seems to be worse than Tweet".to_string(),
42. };

44. summary(post);
45. summary(weibo);

47. println!("{:?}", post);
48. println!("{:?}", weibo);
49. }

51. // 在下面实现 `fn summary` 函数

使用特征作为函数返回值

我们还可以在函数的返回值中使用 impl Trait 语法。然后只有在返回值是同一个类型时,才能这么使用,如果返回值是不同的类型,你可能更需要特征对象。

  1. 🌟🌟
2. struct Sheep {}
3. struct Cow {}

5. trait Animal {
6. fn noise(&self) -> String;
7. }

9. impl Animal for Sheep {
10. fn noise(&self) -> String {
11. "baaaaah!".to_string()
12. }
13. }

15. impl Animal for Cow {
16. fn noise(&self) -> String {
17. "moooooo!".to_string()
18. }
19. }

21. // 返回一个类型,该类型实现了 Animal 特征,但是我们并不能在编译期获知具体返回了哪个类型
22. // 修复这里的错误,你可以使用虚假的随机,也可以使用特征对象
23. fn random_animal(random_number: f64) -> impl Animal {
24. if random_number < 0.5 {
25. Sheep {}
26. } else {
27. Cow {}
28. }
29. }

31. fn main() {
32. let random_number = 0.234;
33. let animal = random_animal(random_number);
34. println!("You've randomly chosen an animal, and it says {}", animal.noise());
35. }

特征约束

impl Trait 语法非常直观简洁,但它实际上是特征约束的语法糖。

当使用泛型参数时,我们往往需要为该参数指定特定的行为,这种指定方式就是通过特征约束来实现的。

  1. 🌟🌟
1. fn main() {
2. assert_eq!(sum(1, 2), 3);
3. }

5. // 通过两种方法使用特征约束来实现 `fn sum`
6. fn sum<T>(x: T, y: T) -> T {
7. x + y
8. }
  1. 🌟🌟
1. // 修复代码中的错误
2. struct Pair<T> {
3. x: T,
4. y: T,
5. }

7. impl<T> Pair<T> {
8. fn new(x: T, y: T) -> Self {
9. Self {
10. x,
11. y,
12. }
13. }
14. }

16. impl<T: std::fmt::Debug + PartialOrd> Pair<T> {
17. fn cmp_display(&self) {
18. if self.x >= self.y {
19. println!("The largest member is x = {:?}", self.x);
20. } else {
21. println!("The largest member is y = {:?}", self.y);
22. }
23. }
24. }

26. struct Unit(i32);

28. fn main() {
29. let pair = Pair{
30. x: Unit(1),
31. y: Unit(3)
32. };

34. pair.cmp_display();
35. }
  1. 🌟🌟🌟
2. // 填空
3. fn example1() {
4. // `T: Trait` 是最常使用的方式
5. // `T: Fn(u32) -> u32` 说明 `T` 只能接收闭包类型的参数
6. struct Cacher<T: Fn(u32) -> u32> {
7. calculation: T,
8. value: Option<u32>,
9. }

11. impl<T: Fn(u32) -> u32> Cacher<T> {
12. fn new(calculation: T) -> Cacher<T> {
13. Cacher {
14. calculation,
15. value: None,
16. }
17. }

19. fn value(&mut self, arg: u32) -> u32 {
20. match self.value {
21. Some(v) => v,
22. None => {
23. let v = (self.calculation)(arg);
24. self.value = Some(v);
25. v
26. },
27. }
28. }
29. }

31. let mut cacher = Cacher::new(|x| x+1);
32. assert_eq!(cacher.value(10), __);
33. assert_eq!(cacher.value(15), __);
34. }

36. fn example2() {
37. // 还可以使用 `where` 来约束 T
38. struct Cacher<T>
39. where T: Fn(u32) -> u32,
40. {
41. calculation: T,
42. value: Option<u32>,
43. }

45. impl<T> Cacher<T>
46. where T: Fn(u32) -> u32,
47. {
48. fn new(calculation: T) -> Cacher<T> {
49. Cacher {
50. calculation,
51. value: None,
52. }
53. }

55. fn value(&mut self, arg: u32) -> u32 {
56. match self.value {
57. Some(v) => v,
58. None => {
59. let v = (self.calculation)(arg);
60. self.value = Some(v);
61. v
62. },
63. }
64. }
65. }

67. let mut cacher = Cacher::new(|x| x+1);
68. assert_eq!(cacher.value(20), __);
69. assert_eq!(cacher.value(25), __);
70. }

73. fn main() {
74. example1();
75. example2();

77. println!("Success!")
78. }

你可以在这里找到答案(在 solutions 路径下)