#mutable is also borrowed as immutable mutable borrow error

6 messages · Page 1 of 1 (latest)

quasi fox
#

hello i am having issues on trying to resolve this error where i am pushing an element into an array, while also reffrencing it

this is the struct that i'm using

struct Ball {
    position: Vector2,
    speed: f32,
    radius: f32,
    color: Color,
}

struct Line<'a> {
    ball_1: &'a Ball,
    ball_2: &'a Ball,
}
while running {
...
        //error is here in _store_ball.push
        if rl.is_mouse_button_pressed(MOUSE_LEFT_BUTTON) {
            _store_ball.push(Ball {
                position: rl.get_mouse_position(),
                speed: 3.0,
                radius: 10.0,
                color: Color::BLACK,
            });

            if _store_ball.len() > 1 {
                _store_line.push(Line {
                    ball_1: &_store_ball[_store_ball.len() - 1],
                    ball_2: &_store_ball[_store_ball.len() - 2],
                })
            }
        }

...

}

i am trying to use a refrence of ball to a make a line

#

mutable is also borrowed as immutable mutable borrow error

glacial oak
#

You cannot do this with Vec, because pushing items will potentially reallocate the vector, invalidating all existing references.
https://docs.rs/typed-arena/ does support "push and get a reference", at the cost of not supporting most other things.
for a more general tool you can store indices instead of references in _store_line.

#

By the way, you shouldn't name variables starting with underscores when you're actually using them. By convention and compiler, they specifically mean "this variable is not actually used, don't give me warnings about it, it is just a placeholder name for discarding something"

quasi fox
#

for the naming yeah, i'm just using it as a place holder for a context manager i'm building up