[SOLVED] Destructure a struct mutably

#1

Consider this structure with 2 fields on the heap that are needed to be updated in unison:

struct Both {
   one: One,
   two: Two,
}

impl Both {
    fn update(&mut self, value: &Value) {
        let mut one_attr = self.one.attr_borrow_mut(value);
        let mut two_attr = self.two.attr_borrow_mut(value);
        // ... mangled update of both one_attr and two_attr.
    }
}

In this code the compiler will complain that self is borrowed mutably more than once.

But is it possible to destructure Both into a &mut to both one and two? Assuming both One and Two are heap allocated, or otherwise have a fixed length, shouldn’t that be safe?


Edit: playground example that sadly fails to show the proper error, since it is is missing a crate.

0 Likes

#2

You should give an example on the playground. This works, is that what you had in mind? Doesn’t have anything to do with heap vs. stack though.

0 Likes

#3

Playground does not have crates that I require, and I am not sure if my question will make seance without them, but I will try…

0 Likes

#4

No need to make it more complicated than what you gave, but as you see, I did not fully understand what you wanted.

That said, this also works, so you’d have to explain why it’s not sufficient (maybe it’s your attr_borrow_mut that I don’t know that doesn’t fit?).

1 Like

#5

Thanks, this helped guiding me the a simpler solution that works.

0 Likes