I have a minimal example of code that implements move semantics for some container:
use std::mem;
impl<'a, T: 'a + ?Sized> Drop for Cointainer<'a, T> {
fn drop(&mut self) {}
}
struct Cointainer<'a, T: 'a + ?Sized> {
item: &'a /* mut */ T,
}
impl<'a, T> Cointainer<'a, T> {
fn mv(self) -> Cointainer<'a, T> {
let new = Cointainer { item: /* &mut */ self.item };
mem::forget(self);
new
}
}
fn main() {}
That compiles and works without any problems.
I realized I will need to mutate the value referenced by Cointainer::item
, so I've made the reference mut
. When I do so, I get:
error[E0505]: cannot move out of `self` because it is borrowed
--> src/main.rs:14:21
|
13 | let new = Cointainer { item: /* &mut */ self.item };
| --------- borrow of `*self.item` occurs here
14 | mem::forget(self);
| ^^^^ move out of `self` occurs here
I need to create a new container and transfer ownership of item
there, and drop the old one.
This example is artificial. The actual "move" operation does some other stuff, and doesn't necessarily return the same container type.