&self is an immutable borrow of the instance — you can read but not modify. &mut self is a mutable borrow — you can read and modify the instance, but only one mutable reference can exist at a time.
&self (immutable borrow):
1struct Counter {2 value: i32,3}45impl Counter {6 fn get(&self) -> i32 {7 self.value // Just read, no modification8 }910 fn is_positive(&self) -> bool {11 self.value > 012 }13}1415let c = Counter { value: 5 };16let v1 = c.get(); // &self borrow17let v2 = c.get(); // Another &self borrow — OK!18println!("{} {}", v1, v2); // 5 5
&mut self (mutable borrow):
1impl Counter {2 fn increment(&mut self) {3 self.value += 1; // Modify the field4 }56 fn set(&mut self, value: i32) {7 self.value = value; // Replace the field8 }9}1011let mut c = Counter { value: 5 };12c.increment(); // &mut self borrow13// let r = &c.value; // Error! Cannot borrow as immutable while &mut exists14println!("{}", c.get()); // 6 — OK after &mut borrow ends
When to use &self:
When to use &mut self:
Common mistakes: