没有被注释的use那一行,就可以正常编译,取消注释就会报下面的错误.这个use语句为什么会导致编译失败呢?.
error[E0368]: binary assignment operation `+=` cannot be applied to type `Rc<RefCell<{integer}>>`
--> src/bin/default.rs:7:5
|
7 | *value.borrow_mut() += 10;
| -------------------^^^^^^
| |
| cannot use `+=` on type `Rc<RefCell<{integer}>>`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0368`.
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);
}
1
共 3 条评论, 1 页
评论区
写评论1
你可以这么理解
的意图是为所有的类型实现
Trait
,当引入Trait
之后,impl生效也是理所当然的事,T
会特化为Rc<_>
。主要与Trait和泛型有关,不理解的话建议先去看看。
2
cannot use
+=on type
Rc<RefCell<{integer}>>``*(res.borrow_mut())
的解引用类型是Rc<_>
,一般来说原类型就是&Rc<_>
或&mut Rc<_>
,再结合impl<T: ?Sized> BorrowMut<T> for T
的函数签名fn borrow_mut(&mut self) -> &mut T
便可知。--
👇
liuzhengrong-github: 非常感谢!但我还有两个地方不太明白:
use std::borrow::BorrowMut;
之后就调用了Rc
的borrow_mut
Rc
的borrow_mut
--
👇
ywxt: ``` #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> BorrowMut for T { fn borrow_mut(&mut self) -> &mut T { self } }
#[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;
非常感谢!但我还有两个地方不太明白:
use std::borrow::BorrowMut;
之后就调用了Rc
的borrow_mut
Rc
的borrow_mut
--
👇
ywxt: ``` #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> BorrowMut for T { fn borrow_mut(&mut self) -> &mut T { self } }
#[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;
你调用的实际上是
Rc
的borrow_mut
这个才是
RefCell
的borrow_mut
,通过显式解引用来避免歧义