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`
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()();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With