为什么没有为包装 FnMut 的 `std::cell::RefMut<'_, [..]>` 实现 DerefMut?
why DerefMut is not implemented for `std::cell::RefMut<'_, [..]>` which wraps FnMut?
我想将 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())();
在调用它之前显式取消引用该值作为可变值。
我想将 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())();
在调用它之前显式取消引用该值作为可变值。