Consider this example:
struct Item {
x: u32,
}
impl Item {
pub fn increment(self, amount: u32) -> Self {
Item { x: self.x + amount }
}
}
struct Container {
item: Item,
}
impl Container {
pub fn increment_item(&mut self, amount: u32) {
// This line causes "cannot move out of borrowed content"
self.item = self.item.increment(amount);
}
}
As you can see, Item.increment
consumes the item and returns a new instance.
In Container.increment_item
I want to replace the current item with the one returned by Item.increment
but the compiler yells at me with a cannot move out of borrowed content
error.
In Container.increment_item
self
is mut
so I can mutate its fields, I don't understand why the compiler doesn't allow me to do it.
I know that I can make Container.increment_item
consumes self
and return a new object, like Item.increment
does, and it works, but I would like to understand why I'm getting the error and how can I fix it when I really can't consume the container.