Search code examples
rustclosuresdereference

Why does a mutable borrow of a closure through DerefMut not work?


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`

Solution

  • 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)();
    

    or by calling DerefMut::deref_mut:

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