< 返回版块

liuzhengrong-github 发表于 2021-04-05 16:43

没有被注释的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);
}

评论区

写评论
ywxt 2021-04-05 18:49

1

你可以这么理解

impl<T: ?Sized> Trait for T{}

的意图是为所有的类型实现Trait,当引入Trait之后,impl生效也是理所当然的事,T会特化为Rc<_>

主要与Trait和泛型有关,不理解的话建议先去看看。

2

cannot use +=on typeRc<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: 非常感谢!但我还有两个地方不太明白:

  1. 为什么 use std::borrow::BorrowMut; 之后就调用了 Rcborrow_mut
  2. 从哪里可以看出这个报错原因是因为调用了Rcborrow_mut

--
👇
ywxt: ``` #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> BorrowMut for T { fn borrow_mut(&mut self) -> &mut T { self } }

你调用的实际上是`Rc`的`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") }

这个才是`RefCell`的`borrow_mut`,

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

通过显式解引用来避免歧义


作者 liuzhengrong-github 2021-04-05 18:00

非常感谢!但我还有两个地方不太明白:

  1. 为什么 use std::borrow::BorrowMut; 之后就调用了 Rcborrow_mut
  2. 从哪里可以看出这个报错原因是因为调用了Rcborrow_mut

--
👇
ywxt: ``` #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> BorrowMut for T { fn borrow_mut(&mut self) -> &mut T { self } }

你调用的实际上是`Rc`的`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") }

这个才是`RefCell`的`borrow_mut`,

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

通过显式解引用来避免歧义

ywxt 2021-04-05 17:18
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> BorrowMut<T> for T {
    fn borrow_mut(&mut self) -> &mut T {
        self
    }
}

你调用的实际上是Rcborrow_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")
}

这个才是RefCellborrow_mut

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

通过显式解引用来避免歧义

1 共 3 条评论, 1 页