use std::cell::RefCell;use std::rc::Rc;// use std::borrow::BorrowMut;fn main(){let value = Rc::new(RefCell::new(5));*value.borrow_mut() += 10;println!("{:?}", value);}
当打开注释的 use 时,返回错误如下:
Compiling playground v0.0.1 (/playground)error[E0368]: binary assignment operation `+=` cannot be applied to type `Rc<RefCell<{integer}>>`--> src/main.rs:7:5|7 | *value.borrow_mut() += 10;| -------------------^^^^^^| || cannot use `+=` on type `Rc<RefCell<{integer}>>`error: aborting due to previous errorFor more information about this error, try `rustc --explain E0368`.
BorrowMut 为所有类型都实现了:
#[stable(feature = "rust1", since = "1.0.0")]impl<T: ?Sized> BorrowMut<T> for T {fn borrow_mut(&mut self) -> &mut T {self}}
当引入 BorrowMut 之后,impl生效也是理所当然的事,T会特化为Rc<_>。*(res.borrow_mut())(此处加不加括号效果是一样的)的解引用类型是Rc<_>,一般来说原类型就是&Rc<_>或&mut Rc<_>。
RefCell borrow_mut 定义如下:
#[stable(feature = "rust1", since = "1.0.0")]#[inline]#[track_caller]pub fn borrow_mut(&self) -> RefMut<'_, T> {self.try_borrow_mut().expect("already borrowed")}
可以通过显示解引用来避免歧义:
use std::ops::Deref;*value.deref().borrow_mut() += 10;
https://rustcc.cn/article?id=843f8aa9-d549-4ac7-9646-05dd6202fe85
