&self = shared, immutable borrow. Multiple &self can coexist. &mut self = exclusive, mutable borrow. Only one &mut self can exist at a time.
&self — immutable access:
1struct Point {2 x: f64,3 y: f64,4}56impl Point {7 fn distance_from_origin(&self) -> f64 {8 (self.x.powi(2) + self.y.powi(2)).sqrt()9 }1011 fn midpoint(&self, other: &Point) -> Point {12 Point {13 x: (self.x + other.x) / 2.0,14 y: (self.y + other.y) / 2.0,15 }16 }17}1819let p = Point { x: 3.0, y: 4.0 };20println!("Distance: {}", p.distance_from_origin()); // 5.0
&mut self — mutable access:
1impl Point {2 fn translate(&mut self, dx: f64, dy: f64) {3 self.x += dx;4 self.y += dy;5 }67 fn scale(&mut self, factor: f64) {8 self.x *= factor;9 self.y *= factor;10 }11}1213let mut p = Point { x: 1.0, y: 2.0 };14p.translate(3.0, 4.0); // (4, 6)15p.scale(2.0); // (8, 12)
When to use &self:
When to use &mut self:
Common mistakes:
let mut for &mut self methods.