Implement methods on a struct by defining an impl block for the struct type and adding functions where the first parameter is self.
struct Point {
x: i32,
y: i32,
}
impl Point {
fn distance(&self, other: &Point) -> f64 {
let dx = other.x - self.x;
let dy = other.y - self.y;
(dx * dx + dy * dy) as f64 .sqrt()
}
}
The &self parameter allows the method to borrow the instance without taking ownership, enabling you to call distance on a Point instance like p1.distance(&p2).