Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple borrow in Rust

Tags:

rust

borrowing

There is any common pattern to implement something like this in Rust?

The error is

cannot borrow `sprite` as mutable because it is also borrowed as immutable

I understand the problem but have no idea how to implement something like this in Rust.

struct Sprite {
    position: i32,
}

impl Sprite {
    pub fn left(&mut self) {
        self.position += 1;
    }
}

struct Game<'g> {
    sprite: &'g Sprite,
}

impl<'g> Game<'g> {
    pub fn new(sprite: &Sprite) -> Game {
        Game { sprite: sprite }
    }
}

fn main() {
    let mut sprite = Sprite { position: 3 };

    let game = Game::new(&sprite);

    sprite.left();
}

The code is also available on the playground.

like image 312
fazibear Avatar asked Jul 08 '26 09:07

fazibear


1 Answers

Intuitively, Games should probably own their Sprites. Here is an updated version reflecting that design change. Also on the playground.

struct Sprite {
    position: i32,
}

impl Sprite {
    pub fn left(&mut self) {
        self.position += 1;
    }
}

struct Game {
    sprite: Sprite,
}

impl Game {
    pub fn new(sprite: Sprite) -> Game {
        Game {
            sprite: sprite
        }
    }
}


fn main() {
    let sprite = Sprite{ position: 3 };

    let mut game = Game::new(sprite);

    game.sprite.left();
}
like image 114
Michael Hewson Avatar answered Jul 11 '26 15:07

Michael Hewson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!