Why does volatile closing borrowing through DerefMut not work?

I am trying to easily replace a mutable variable. Derefand DerefMutimplemented for Foobut compilation failure:

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
+4
source share
1 answer

This is a known issue regarding the way features are deduced through Deref. As a workaround, you need to explicitly get a mutable link:

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

or

let mut t = Foo;
t.deref_mut()();
+2
source

Source: https://habr.com/ru/post/1686552/


All Articles