fazibear
fazibear

Reputation: 147

Multiple borrow in Rust

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.

Upvotes: 3

Views: 2309

Answers (1)

Michael Hewson
Michael Hewson

Reputation: 1534

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();
}

Upvotes: 2

Related Questions