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

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

问题描述

我正在尝试可变地借用可变变量。 Foo 实现了 Deref DerefMut ,但是编译失败:

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天全站免登陆