代码之家  ›  专栏  ›  技术社区  ›  chabapok

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

  •  6
  • chabapok  · 技术社区  · 7 年前

    我试图可变地借用一个可变变量。 Deref 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`
    
    1 回复  |  直到 5 年前
        1
  •  5
  •   Shepmaster Tim Diekmann    5 年前

    这是 a known issue 关于如何通过 Deref . 作为一种解决方法,您需要通过执行可变重新箭头显式获取可变引用:

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

    或者打电话 DerefMut::deref_mut :

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