为什么通过 DerefMut 对闭包的可变借用不起作用? [英] Why does a mutable borrow of a closure through DerefMut not work?

查看:23
本文介绍了为什么通过 DerefMut 对闭包的可变借用不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to mutably borrow a mutable variable. Deref and DerefMut are implemented for Foo, but compilation fails:

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

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

Newer versions of the compiler have an updated error message:

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关于如何通过 Deref 推断函数特征的已知问题.作为一种解决方法,您需要通过执行可变重新借用来显式获取可变引用:

This is a known issue regarding how the function traits are inferred through Deref. As a workaround, you need to explicitly get a mutable reference by doing a mutable reborrow:

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

或通过调用DerefMut::deref_mut:

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

这篇关于为什么通过 DerefMut 对闭包的可变借用不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆