&self borrows the instance immutably — you can read data but not change it. &mut self borrows the instance mutably — you can both read and write, but exclusively (no other references allowed simultaneously).
&self — immutable borrow:
1struct BankAccount {2 balance: f64,3 owner: String,4}56impl BankAccount {7 fn balance(&self) -> f64 {8 self.balance9 }1011 fn owner(&self) -> &str {12 &self.owner13 }14}1516let account = BankAccount { balance: 1000.0, owner: "Alice".into() };17let b = account.balance(); // &self18let o = account.owner(); // Another &self — fine!19println!("{}: {}", o, b); // Alice: 1000
&mut self — mutable borrow:
1impl BankAccount {2 fn deposit(&mut self, amount: f64) {3 self.balance += amount;4 }56 fn withdraw(&mut self, amount: f64) -> bool {7 if self.balance >= amount {8 self.balance -= amount;9 true10 } else {11 false12 }13 }14}1516let mut account = BankAccount { balance: 1000.0, owner: "Alice".into() };17account.deposit(500.0); // &mut self18account.withdraw(200.0); // &mut self19println!("{}", account.balance()); // 1300
When to use &self:
When to use &mut self:
&mut Self.Common mistakes:
let mut).