About "Rust automatically adds in & , &mut , or *"
โ Rust ๐ 2026-01-19 ๐ค surdeus ๐๏ธ 4According to "The Rust Programming Language" ch05-03
Hereโs how it works: When you call a method with object.something() , Rust automatically adds in & , &mut , or * so that object matches the signature of the method. In other words, the following are the same:
My question is about this code
let value = Rc::new(RefCell::new(5));
*value.borrow_mut() += 10;
I can understand why value.borrow_mut() will automatic compile to (*value).borrow_mut()
But why I should add * before value.borrow_mut() for the next add operation
This is the docs about += operator
fn add_assign(&mut self, rhs: Rhs);
In my understanding *value.borrow_mut() += 10; equals to
*value.borrow_mut().add_assign(10);
It still call a method,so why the compiler doesn't automatic add * before value.borrow_mut()?
It just like this example
let mut a = 3;
let mut b = &mut a;
*b += 1;
// Why B should add * before
If I am wrong, please point it out.
Thanks for your answer
6 posts - 3 participants
๐ท๏ธ Rust_feed