From 6947ef48cc15caebdffef7071c823244a66e0675 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 18:47:52 -0400 Subject: [PATCH] Add back automatic referencing as a box --- src/ch05-01-method-syntax.md | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/ch05-01-method-syntax.md b/src/ch05-01-method-syntax.md index 1ef77ae..0e1f9eb 100644 --- a/src/ch05-01-method-syntax.md +++ b/src/ch05-01-method-syntax.md @@ -69,6 +69,51 @@ signature, is for organization. We've put all the things we can do with an instance of a type together in one `impl` block, rather than make future users of our code search for capabilities of `Rectangle` all over the place. + + +#### Where's the `->` operator? + +In C++, there are two different operators for calling methods: `.` if you're +calling a method on the object directly, and `->` if you're calling the method +on a pointer to the object and thus need to dereference the pointer first. Rust +doesn't have an equivalent to the `->` operator; instead, Rust has a feature +called *automatic referencing*. Calling methods is one of the few places in +Rust that has behavior like this. + +Here’s how it works: when you call a method with `object.something(`, Rust will +automatically add in `&`s or `&mut`s so that `object` matches the signature of +the method. In other words, these are the same: + +```rust +# #[derive(Debug,Copy,Clone)] +# struct Point { +# x: f64, +# y: f64, +# } +# +# impl Point { +# fn distance(&self, other: &Point) -> f64 { +# let x_squared = f64::powi(other.x - self.x, 2); +# let y_squared = f64::powi(other.y - self.y, 2); +# +# f64::sqrt(x_squared + y_squared) +# } +# } +# let p1 = Point { x: 0.0, y: 0.0 }; +# let p2 = Point { x: 5.0, y: 6.5 }; +p1.distance(&p2); +(&p1).distance(&p2); +``` + +The first one looks much, much cleaner. This automatic referencing behavior +works because methods have a clear receiver — the type of `self`. Given the +receiver and name of a method, Rust can figure out definitively whether the +method is just reading (so needs `&self`), mutating (so `&mut self`), or +consuming (so `self`). The fact that Rust makes borrowing implicit for method +receivers is a big part of making ownership ergonomic in practice. + + + ### Methods with More Arguments Let's practice some more with methods by implementing a second method on our