0

Imagine this scenario: you have an object containing an iterable. You want to call a function implemented on the same object, which doing mutation on another member of the "self", lets say to use an sqlite connection or draw content to an sdl canvas, based on the content of our array.

You cant do that on a trivial way because when you setting up your foreach loop you borrowing the self, and cant borrow it again with mutability.

Is there any solution for this? How rust people dealing with objects if the whole struct either referenced mutable or immutable and we cant deal with individual members separately?

struct Stuff (i32, Vec<(i32, char)>);
impl Stuff {
    fn fun1(&mut self) {
        for item in &self.1  { //borrowing immutable
            self.0 += item.0; // this works fine
            self.do_mutation(); // but here im trying to borrow it mutable and
                                // it is making the cute crab angry and sad.
            dbg!((item.1, self.0));
        }
    }
    
    
    fn do_mutation(&mut self) {
        //another function doing some crazy stuff...
    }
    
}
    
fn main() {
    let mut object = Stuff(0, vec![(1,'a'),(2,'b'),(3,'c')]);
    object.fun1();
}
SurGe
  • 23
  • 3
  • You give `do_mutation` the right to modify all members of `Stuff`, including `1`. Can't have that. Consider giving `do_mutation` only `&mut self.0` instead. – Caesar Apr 08 '22 at 00:22
  • That's a solution but then I use all the convinience of objects. What if I have multiple members, and want to modify plenty of them. – SurGe Apr 08 '22 at 00:33
  • Create a substruct. Really, there is no other solution to that that doesn't involve rearranging your code. – Chayim Friedman Apr 08 '22 at 00:54
  • @ChayimFriedman yes it is an answer, but isn't it a dessing flaw in rust? – SurGe Apr 08 '22 at 00:55
  • First, it is not as terrible as it sounds. You get used to it, and design your API accordingly. However, this is something the Rust time is definitely aware of. See for example [this post](https://smallcultfollowing.com/babysteps/blog/2021/11/05/view-types/) about an idea how to fix that. – Chayim Friedman Apr 08 '22 at 01:15

0 Answers0