How do I change an attribute on a struct to a new value which contains the old value?
struct Container {
more: Box<Container>
}
struct ContainerBox {
container: Option<Container>
}
impl ContainerBox {
pub fn ingest(&mut self, container: Container) {
match &self.container {
Some(container) => {
self.container = Some(Container { more: (*container).clone() }); // this doesn't look right.
},
None => self.container = Some(container)
};
}
}
Very silly example but it gets the point across. I have a struct that owns some data that may be something or nothing, when its something, I need to replace it with a new instance of the same type which is composed of the old value in that structs attribute.
I think I understand why the borrow checker is unhappy, but I also can’t see another way to write this.
>Solution :
You can use Option::take():
impl ContainerBox {
pub fn ingest(&mut self, container: Container) {
match self.container.take() {
Some(container) => {
self.container = Some(Container { more: Box::new(container) });
},
None => self.container = Some(container),
};
}
}