为什么在索引到不可变的 Vec<RefCell> 后不能调用borrow_mut()? [英] Why can I not call borrow_mut() after indexing into an immutable Vec&lt;RefCell&gt;?

查看:42
本文介绍了为什么在索引到不可变的 Vec<RefCell> 后不能调用borrow_mut()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's try to compile this code:

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() {}

编译错误:

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

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

Why does this code require adding &mut self to function signature in order to compile?

推荐答案

这是一个已知问题,其中 IndexMut 有时会在实际使用 Index 时被选中.

This is a known issue where IndexMut is sometimes selected when Index should actually be used.

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

Your workaround of using {} is reasonable, but you can also use Index explicitly:

use std::cell::RefCell;

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

fn main() {}

另见:

这篇关于为什么在索引到不可变的 Vec<RefCell> 后不能调用borrow_mut()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆