关于rust:为什么通过DerefMut可变地借用一个关闭操作无效?

Why does a mutable borrow of a closure through DerefMut not work?

我试图可变地借用一个可变变量。 DerefDerefMutFoo实现,但编译失败:

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`


这是有关如何通过Deref推断功能特征的已知问题。 解决方法是,您需要通过进行可变的重新借用来显式地获取可变的引用:

1
2
let mut t = Foo;
(&mut *t)();

或致电DerefMut::deref_mut

1
2
let mut t = Foo;
t.deref_mut()();