1
- # Methods
1
+ # Associated functions & Methods
2
2
3
- Methods are functions attached to objects. These methods have access to the
4
- data of the object and its other methods via the ` self ` keyword. Methods are
5
- defined under an ` impl ` block.
3
+ Some functions are connected to a particular type. These come in two forms:
4
+ associated functions, and methods. Associated functions are functions that
5
+ are defined on a type generally, while methods are associated functions that are
6
+ called on a particular instance of a type.
6
7
7
8
``` rust,editable
8
9
struct Point {
9
10
x: f64,
10
11
y: f64,
11
12
}
12
13
13
- // Implementation block, all `Point` methods go in here
14
+ // Implementation block, all `Point` associated functions & methods go in here
14
15
impl Point {
15
- // This is a static method
16
- // Static methods don't need to be called by an instance
17
- // These methods are generally used as constructors
16
+ // This is an "associated function" because this function is associated with
17
+ // a particular type, that is, Point.
18
+ //
19
+ // Associated functions don't need to be called with an instance.
20
+ // These functions are generally used like constructors.
18
21
fn origin() -> Point {
19
22
Point { x: 0.0, y: 0.0 }
20
23
}
21
24
22
- // Another static method , taking two arguments:
25
+ // Another associated function , taking two arguments:
23
26
fn new(x: f64, y: f64) -> Point {
24
27
Point { x: x, y: y }
25
28
}
@@ -31,7 +34,7 @@ struct Rectangle {
31
34
}
32
35
33
36
impl Rectangle {
34
- // This is an instance method
37
+ // This is a method
35
38
// `&self` is sugar for `self: &Self`, where `Self` is the type of the
36
39
// caller object. In this case `Self` = `Rectangle`
37
40
fn area(&self) -> f64 {
@@ -80,12 +83,12 @@ impl Pair {
80
83
81
84
fn main() {
82
85
let rectangle = Rectangle {
83
- // Static methods are called using double colons
86
+ // Associated functions are called using double colons
84
87
p1: Point::origin(),
85
88
p2: Point::new(3.0, 4.0),
86
89
};
87
90
88
- // Instance methods are called using the dot operator
91
+ // Methods are called using the dot operator
89
92
// Note that the first argument `&self` is implicitly passed, i.e.
90
93
// `rectangle.perimeter()` === `Rectangle::perimeter(&rectangle)`
91
94
println!("Rectangle perimeter: {}", rectangle.perimeter());
@@ -112,4 +115,4 @@ fn main() {
112
115
//pair.destroy();
113
116
// TODO ^ Try uncommenting this line
114
117
}
115
- ```
118
+ ```
0 commit comments