方法

方法是从属于对象的函数(Mathods are functions attached to objects)。这些方法通过 关键字 self 来访问对象中的数据和其他方法。方法在 impl 代码块下定义。

1. struct Point {
2. x: f64,
3. y: f64,
4. }

6. // 实现的代码块,所有的 `Point` 方法都在这里给出
7. impl Point {
8. // 这是一个静态方法(static method)
9. // 静态方法不需要通过实例来调用
10. // 这类方法一般用作构造器(constructor)
11. fn origin() -> Point {
12. Point { x: 0.0, y: 0.0 }
13. }

15. // 另外一个静态方法,带有两个参数:
16. fn new(x: f64, y: f64) -> Point {
17. Point { x: x, y: y }
18. }
19. }

21. struct Rectangle {
22. p1: Point,
23. p2: Point,
24. }

26. impl Rectangle {
27. // 这是实例方法(instance method)
28. // `&self` 是 `self: &Self` 的语法糖(sugar),其中 `Self` 是所调用对象
29. // 的类型。在这个例子中 `Self` = `Rectangle`
30. fn area(&self) -> f64 {
31. // `self` 通过点运算符来访问结构体字段
32. let Point { x: x1, y: y1 } = self.p1;
33. let Point { x: x2, y: y2 } = self.p2;

35. // `abs` 是一个 `f64` 类型的方法,返回调用者的绝对值
36. ((x1 - x2) * (y1 - y2)).abs()
37. }

39. fn perimeter(&self) -> f64 {
40. let Point { x: x1, y: y1 } = self.p1;
41. let Point { x: x2, y: y2 } = self.p2;

43. 2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
44. }

46. // 这个方法要求调用者对象是可变的
47. // `&mut self` 为 `self: &mut Self` 的语法糖
48. fn translate(&mut self, x: f64, y: f64) {
49. self.p1.x += x;
50. self.p2.x += x;

52. self.p1.y += y;
53. self.p2.y += y;
54. }
55. }

57. // `Pair` 含有的资源:两个堆分配的整型
58. struct Pair(Box<i32>, Box<i32>);

60. impl Pair {
61. // 这个方法“消费”调用者对象的资源
62. // `self` 为 `self: Self` 的语法糖
63. fn destroy(self) {
64. // 解构 `self`
65. let Pair(first, second) = self;

67. println!("Destroying Pair({}, {})", first, second);

69. // `first` 和 `second` 离开作用域后释放
70. }
71. }

73. fn main() {
74. let rectangle = Rectangle {
75. // 静态方法使用双重冒号来调用
76. p1: Point::origin(),
77. p2: Point::new(3.0, 4.0),
78. };

80. // 实例方法通过点运算符来调用
81. // 注意第一个参数 `&self` 是隐式传递的,比如:
82. // `rectangle.perimeter()` === `Rectangle::perimeter(&rectangle)`
83. println!("Rectangle perimeter: {}", rectangle.perimeter());
84. println!("Rectangle area: {}", rectangle.area());

86. let mut square = Rectangle {
87. p1: Point::origin(),
88. p2: Point::new(1.0, 1.0),
89. };

91. // 报错! `rectangle` 是不可变的,但这方法需要一个可变对象
92. //rectangle.translate(1.0, 0.0);
93. // 试一试 ^ 将此行注释去掉

95. // 正常运行!可变对象可以调用可变方法
96. square.translate(1.0, 1.0);

98. let pair = Pair(Box::new(1), Box::new(2));

100. pair.destroy();

102. // 报错!前面的 `destroy` 调用“消费了” `pair`
103. //pair.destroy();
104. // 试一试 ^ 将此行注释去掉
105. }