相关疑难解决方法(0)

为什么我不能在索引到不可变的Vec <RefCell>之后调用borrow_mut()?

让我们尝试编译这段代码:

use std::cell::RefCell;

struct Foo {
    v: Vec<RefCell<u8>>,
}

impl Foo {
    fn f(&self, i: usize) {
        let t = &mut *self.v[i].borrow_mut();
        //let t = &mut *{self.v[i].borrow_mut()}; //compiled ok
    }
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

编译错误:

error[E0596]: cannot borrow field `self.v` of immutable binding as mutable
 --> src/main.rs:9:23
  |
8 |     fn f(&self, i: usize) {
  |          ----- use `&mut self` here to make mutable
9 |         let t = &mut *self.v[i].borrow_mut();
  |                       ^^^^^^ cannot mutably borrow field of immutable binding …
Run Code Online (Sandbox Code Playgroud)

rust

7
推荐指数
1
解决办法
138
查看次数

标签 统计

rust ×1