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

cha*_*pok 7 rust

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

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)

为什么这段代码需要添加&mut self到函数签名才能编译?

She*_*ter 7

这是一个已知问题,IndexMut有时Index应该在实际使用时选择.

您使用的解决方法{}是合理的,但您也可以Index明确使用:

use std::cell::RefCell;

fn f(v: Vec<RefCell<u8>>) {
    use std::ops::Index;
    let _t = &mut v.index(0).borrow_mut();
}

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

也可以看看: