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

2023-12-23

我正在尝试可变地借用可变变量。Deref and DerefMut实施用于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`

This is 一个已知问题 https://github.com/rust-lang/rust/issues/26186关于如何通过以下方式推断功能特征Deref。作为解决方法,您需要通过执行可变重新借用来显式获取可变引用:

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

或通过致电DerefMut::deref_mut:

let mut t = Foo;
t.deref_mut()();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么通过 DerefMut 闭包的可变借用不起作用? 的相关文章

随机推荐