我想将FnMut
闭包包裹在RefCell
中,如下所示:
fn borrow_mut_closure() {
let mut temp = 3i32;
let cl = RefCell::new(move || {
temp += 1;
println!("{}", temp);
});
cl.borrow_mut()();
}
但是令我惊讶的是,编译器报告:
cannot borrow data in a dereference of `std::cell::RefMut<'_, [closure@src/main.rs:17:25: 20:4 temp:i32]>` as mutable
cannot borrow as mutable
help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `std::cell::RefMut<'_, [closure@src/main.rs:17:25: 20:4 temp:i32]>`rustc(E0596)
但是为什么不为此而实施?我该如何克服?
这看起来像是编译器错误。似乎这里报道的可能是同一问题:Cannot borrow as mutable despite DerefMut。
如果您进行更改,您的代码将可用
cl.borrow_mut()();
改为成为
(&mut *cl.borrow_mut())();
在调用它之前将值显式地取消引用为可变的。