如何将结构体的属性更改为包含旧值的新值?

huangapple go评论79阅读模式
英文:

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&lt;Container&gt;
}

struct ContainerBox {
    container: Option&lt;Container&gt;
}

impl ContainerBox {
    pub fn ingest(&amp;mut self, container: Container) {
        match &amp;self.container {
            Some(container) =&gt; {
                self.container = Some(Container { more: (*container).clone() }); // this doesn&#39;t look right.
            },
            None =&gt; 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(&amp;mut self, container: Container) {
        match self.container.take() {
            Some(container) =&gt; {
                self.container = Some(Container { more: Box::new(container) });
            },
            None =&gt; self.container = Some(container),
        };
    }
}

huangapple
  • 本文由 发表于 2023年7月17日 23:28:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定