]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/method-syntax.md
Rollup merge of #21357 - kimroen:patch-1, r=sanxiyn
[rust.git] / src / doc / trpl / method-syntax.md
1 % Method Syntax
2
3 Functions are great, but if you want to call a bunch of them on some data, it
4 can be awkward. Consider this code:
5
6 ```{rust,ignore}
7 baz(bar(foo(x)));
8 ```
9
10 We would read this left-to right, and so we see "baz bar foo." But this isn't the
11 order that the functions would get called in, that's inside-out: "foo bar baz."
12 Wouldn't it be nice if we could do this instead?
13
14 ```{rust,ignore}
15 x.foo().bar().baz();
16 ```
17
18 Luckily, as you may have guessed with the leading question, you can! Rust provides
19 the ability to use this *method call syntax* via the `impl` keyword.
20
21 Here's how it works:
22
23 ```{rust}
24 struct Circle {
25     x: f64,
26     y: f64,
27     radius: f64,
28 }
29
30 impl Circle {
31     fn area(&self) -> f64 {
32         std::f64::consts::PI * (self.radius * self.radius)
33     }
34 }
35
36 fn main() {
37     let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };
38     println!("{}", c.area());
39 }
40 ```
41
42 This will print `12.566371`.
43
44 We've made a struct that represents a circle. We then write an `impl` block,
45 and inside it, define a method, `area`. Methods take a  special first
46 parameter, `&self`. There are three variants: `self`, `&self`, and `&mut self`.
47 You can think of this first parameter as being the `x` in `x.foo()`. The three
48 variants correspond to the three kinds of thing `x` could be: `self` if it's
49 just a value on the stack, `&self` if it's a reference, and `&mut self` if it's
50 a mutable reference. We should default to using `&self`, as it's the most
51 common.
52
53 Finally, as you may remember, the value of the area of a circle is `π*r²`.
54 Because we took the `&self` parameter to `area`, we can use it just like any
55 other parameter. Because we know it's a `Circle`, we can access the `radius`
56 just like we would with any other struct. An import of π and some
57 multiplications later, and we have our area.
58
59 You can also define methods that do not take a `self` parameter. Here's a
60 pattern that's very common in Rust code:
61
62 ```{rust}
63 # #![allow(non_shorthand_field_patterns)]
64 struct Circle {
65     x: f64,
66     y: f64,
67     radius: f64,
68 }
69
70 impl Circle {
71     fn new(x: f64, y: f64, radius: f64) -> Circle {
72         Circle {
73             x: x,
74             y: y,
75             radius: radius,
76         }
77     }
78 }
79
80 fn main() {
81     let c = Circle::new(0.0, 0.0, 2.0);
82 }
83 ```
84
85 This *static method* builds a new `Circle` for us. Note that static methods
86 are called with the `Struct::method()` syntax, rather than the `ref.method()`
87 syntax.
88