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

时间:2017-09-28 14:47:31

标签: rust

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

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

1 个答案:

答案 0 :(得分:4)

这是关于如何通过Deref推断出功能特征的a known issue。作为一种解决方法,您需要显式获取可变引用:

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

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