gpt4 book ai didi

rust - 为什么我不能在索引到不可变的 Vec 后调用 borrow_mut()?

转载 作者:行者123 更新时间:2023-11-29 08:20:16 26 4
gpt4 key购买 nike

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

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才能编译?

最佳答案

这是一个 known issue当实际应该使用 Index 时,有时会选择 IndexMut

您使用 {} 的解决方法是合理的,但您也可以显式使用 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() {}

另见:

关于rust - 为什么我不能在索引到不可变的 Vec<RefCell> 后调用 borrow_mut()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com