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:
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?
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.
31 fn area(&self) -> f64 {
32 std::f64::consts::PI * (self.radius * self.radius)
37 let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };
38 println!("{}", c.area());
42 This will print `12.566371`.
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
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.
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:
63 # #![allow(non_shorthand_field_patterns)]
71 fn new(x: f64, y: f64, radius: f64) -> Circle {
81 let c = Circle::new(0.0, 0.0, 2.0);
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()`