Implement a method for a struct
-
impl
-
self
-
&self
-
We can add methods to a
structusing theimplkeyword (we implement the method). -
The first parameter of every method must be the variable name
selfthat will represent the current instance. -
We can have either
selfor&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
selfthe 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