Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change an attribute on a struct to a new value which contains the old value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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),
        };
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading