1

在 Rust 中实现这样的东西有什么共同的模式吗?

错误是

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

我理解这个问题,但不知道如何在 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();
}

该代码也可在操场上获得。

4

1 回答 1

2

直觉上,Games 可能应该拥有他们Sprite的 s。这是反映该设计更改的更新版本。也在操场上。

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();
}
于 2017-03-29T22:39:56.783 回答