Implement a method for a struct
-
impl
-
self
-
&self
-
We can add methods to a
struct
using theimpl
keyword (we implement the method). -
The first parameter of every method must be the variable name
self
that will represent the current instance. -
We can have either
self
or&self
. The latter will borrow the instance and it will allow us to call two methods (or the same method twice as in our example). -
If we used only
self
the instance would be moved on the first method call. Rarely used.
struct Point { x: f64, y: f64, } impl Point { fn distance(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() } } fn main() { let pnt = Point { x: 2.0, y: 3.0 }; println!("x: {}", pnt.x); println!("y: {}", pnt.y); println!("Distance from origo: {}", pnt.distance()); println!("Distance from origo: {}", pnt.distance()); }
x: 2
y: 3
Distance from origo: 3.605551275463989
Distance from origo: 3.605551275463989