为什么通过DerefMut进行的可变闭包借用不能工作?

6

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

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`

1
t.deref_mut()()可以工作。有趣。 - Lukas Kalbertodt
1个回答

5

这是与通过Deref推断函数特征有关的已知问题。 作为解决方法,您需要通过可变重借来显式地获取可变引用:

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

或通过调用DerefMut :: deref_mut

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

1
鉴于这只是一个解决方法,我真的更喜欢使用方法名称。它使查找模式更容易(搜索deref_mut()()。 - Matthieu M.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接