为什么通过 DerefMut 可变借用闭包不起作用?

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

我正在尝试可变地借用一个可变变量。 DerefDerefMut是为Foo实现的,但是编译失败:

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();
}
error[E0596]: cannot borrow immutable borrowed content as mutable
  --> src/main.rs:20:5
   |
20 |     t();
   |     ^ cannot borrow as mutable

较新版本的编译器更新了错误消息:

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`

这是a known issue关于如何通过Deref推断函数特征。作为解决方法,您需要通过执行可变重新借用来显式获取可变引用:

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

或通过调用 DerefMut::deref_mut:

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