Why does a mutable borrow of a closure through DerefMut not work?
我试图可变地借用一个可变变量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | use std::ops::{Deref, DerefMut}; struct Foo; impl Deref for Foo { type Target = FnMut() + 'static; fn deref(&self) -> &Self::Target { unimplemented!() } } impl DerefMut for Foo { fn deref_mut(&mut self) -> &mut Self::Target { unimplemented!() } } fn main() { let mut t = Foo; t(); } |
1 2 3 4 5 | error[E0596]: cannot borrow immutable borrowed content as mutable --> src/main.rs:20:5 | 20 | t(); | ^ cannot borrow as mutable |
较新版本的编译器具有更新的错误消息:
1 2 3 4 5 6 7 | error[E0596]: cannot borrow data in a dereference of `Foo` as mutable --> src/main.rs:20:5 | 20 | t(); | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Foo` |
这是有关如何通过
1 2 | let mut t = Foo; (&mut *t)(); |
或致电
1 2 | let mut t = Foo; t.deref_mut()(); |