在Rust中多次借用

时间:2017-03-29 20:27:55

标签: rust borrowing

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

此代码也可在playground上找到。

1 个答案:

答案 0 :(得分:2)

直观地说,Game应该拥有他们的Sprite。这是一个反映设计变更的更新版本。也在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();
}