让我们尝试编译这段代码:
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
才能编译?
这是一个已知问题,有时在实际应该使用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() {}
另请参阅:
- 为什么通过 DerefMut 对闭包的可变借用不起作用?
- 如何使用"RefCell"中包含的"BorrowMut"?
另一种解决方法是显式调用RefCell::borrow_mut(&v[0])
。