英文:
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() }); // 这看起来不太对。
},
None => self.container = Some(container)
};
}
}
非常愚蠢的示例,但它传达了要点。我有一个拥有某些数据的结构体,这些数据可能是有也可能没有,当它有值时,我需要用包含该结构体属性中旧值的相同类型的新实例来替换它。
我认为我理解为什么借用检查器不高兴,但我也看不到另一种编写此代码的方法。
英文:
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.
答案1
得分: 1
你可以使用 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),
};
}
}
英文:
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),
};
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论