The following code fails to compile because MutRef is not Copy
. It can not be made copy because &\'a mut i32
is not Copy. Is there any way give
No.
The name for this feature is "implicit reborrowing" and it happens when you pass a &mut
reference where the compiler expects a &mut
reference of a possibly different lifetime. The compiler only implicitly reborrows when the actual type and the expected type are both &mut
references. It does not work with generic arguments or structs that contain &mut
references. There is no way in current Rust to make a custom type that can be implicitly reborrowed.
However, you can implement your own method to explicitly reborrow:
impl<'a> MutRef<'a> {
// equivalent to fn reborrow(&mut self) -> MutRef<'_>
fn reborrow<'b>(&'b mut self) -> MutRef<'b> {
MutRef {v: self.v}
}
}
fn wrapper() {
let mut s: i32 = 9;
let mut q = MutRef{ v: &mut s };
wrapper_use(q.reborrow()); // does not move q
wrapper_use(q); // moves q
}