繁体   English   中英

在Rust中多次借用

[英]Multiple borrow in Rust

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

该代码也可以在操场上找到

直观地讲, Game可能应该拥有自己的Sprite 这是反映该设计更改的更新版本。 也在操场上

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM