samedi 11 juillet 2020

Rust lang stateful machine api design

i'm learning rust, and i have a problem with the design of some sort of stateful machine a minimal example would be something like:

struct Bar {
    x: u32
}

struct Foo {
    v: Vec<Bar>,
}

impl Foo {
    fn foo(&mut self, x: usize) {
        self.bar(&self.v[x]);
    }

    fn bar(&mut self, b: &Bar) {
        self.v.push(Bar{x: b.x});
    }
}

the problem is obviusly the compiler error: "cannot borrow *self as mutable because it is also borrowed as immutable", at the line: "self.bar(&self.v[x])" i pretty much understand the error and i'm lookin for some ways to solve the problem, as i know for a fact that i'm not mutating the vector "v", i already know the RefCell method, and i'm looking far all the possibilities just for better understanding of rust.

I'm open with any ideas, thanks everyone!

Aucun commentaire:

Enregistrer un commentaire