我试图可变地借用一个可变变量。 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
答案 0 :(得分:4)
这是关于如何通过Deref
推断出功能特征的a known issue。作为一种解决方法,您需要显式获取可变引用:
let mut t = Foo;
(&mut *t)();
或
let mut t = Foo;
t.deref_mut()();