1. use std::cell::RefCell;
    2. use std::rc::Rc;
    3. // use std::borrow::BorrowMut;
    4. fn main(){
    5. let value = Rc::new(RefCell::new(5));
    6. *value.borrow_mut() += 10;
    7. println!("{:?}", value);
    8. }

    当打开注释的 use 时,返回错误如下:

    1. Compiling playground v0.0.1 (/playground)
    2. error[E0368]: binary assignment operation `+=` cannot be applied to type `Rc<RefCell<{integer}>>`
    3. --> src/main.rs:7:5
    4. |
    5. 7 | *value.borrow_mut() += 10;
    6. | -------------------^^^^^^
    7. | |
    8. | cannot use `+=` on type `Rc<RefCell<{integer}>>`
    9. error: aborting due to previous error
    10. For more information about this error, try `rustc --explain E0368`.

    BorrowMut 为所有类型都实现了:

    1. #[stable(feature = "rust1", since = "1.0.0")]
    2. impl<T: ?Sized> BorrowMut<T> for T {
    3. fn borrow_mut(&mut self) -> &mut T {
    4. self
    5. }
    6. }

    当引入 BorrowMut 之后,impl生效也是理所当然的事,T会特化为Rc<_>
    *(res.borrow_mut())此处加不加括号效果是一样的)的解引用类型是Rc<_>,一般来说原类型就是&Rc<_>&mut Rc<_>

    RefCell borrow_mut 定义如下:

    1. #[stable(feature = "rust1", since = "1.0.0")]
    2. #[inline]
    3. #[track_caller]
    4. pub fn borrow_mut(&self) -> RefMut<'_, T> {
    5. self.try_borrow_mut().expect("already borrowed")
    6. }

    可以通过显示解引用来避免歧义:

    1. use std::ops::Deref;
    2. *value.deref().borrow_mut() += 10;

    https://rustcc.cn/article?id=843f8aa9-d549-4ac7-9646-05dd6202fe85