Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 借用游戏大师(自我)到游戏状态_Rust_Game Engine_2d Games_Game Development - Fatal编程技术网

Rust 借用游戏大师(自我)到游戏状态

Rust 借用游戏大师(自我)到游戏状态,rust,game-engine,2d-games,game-development,Rust,Game Engine,2d Games,Game Development,我是个新手,我一直在尝试一个简单的游戏 现在,通常在C++或C语言中,我将围绕一个“主”类的实例来构造游戏,该类负责设置、框架限制、窗口创建、事件处理等,以及由主类保存的“状态”类。在创建state类(类似于game\u master*)时,我会传递一个指向master类的指针,以便state类可以访问master类的资源 在Rust中,我无法传递&mut self,因为该状态可能会超过引用 pub fn new(_ctx: &mut Context) -> GameMaster

我是个新手,我一直在尝试一个简单的游戏

现在,通常在C++或C语言中,我将围绕一个“主”类的实例来构造游戏,该类负责设置、框架限制、窗口创建、事件处理等,以及由主类保存的“状态”类。在创建state类(类似于

game\u master*
)时,我会传递一个指向master类的指针,以便state类可以访问master类的资源

在Rust中,我无法传递
&mut self
,因为该状态可能会超过引用

pub fn new(_ctx: &mut Context) -> GameMaster {
    let game = GameMaster {
        state: None,
        pending_state: None
    };

    game.state = Some(Box::new(TestState::new_with_master(&mut game))) <----- NOPE
    game
}
pub fn new(&ctx:&mut Context)->GameMaster{
让游戏=游戏大师{
国家:无,
挂起状态:无
};
game.state=Some(Box::new(TestState::new_with_master(&mut game)))游戏结果{
如果self.state.is_some(){

(*self.state.as_mut()

  • 在任何地方都使用
    Rc
    。如果需要对这些对象进行垃圾收集,请记住也要使用
    Weak
    ,或者添加特殊的销毁方法,因为它们相互引用

  • 使用原始指针和不安全的代码。问题是,使用不安全的遵从性,除了生存期检查外,还将丢失可变性检查(
    RefCell
    确保一次只存在一个可变引用)


  • 我不久前也遇到过类似的问题,但我认为唯一的选择是:

  • 在任何地方都使用
    Rc
    。如果需要对这些对象进行垃圾收集,请记住也要使用
    Weak
    ,或者添加特殊的销毁方法,因为它们相互引用

  • 使用原始指针和不安全的代码。问题是,使用不安全的遵从性,除了生存期检查外,还将丢失可变性检查(
    RefCell
    确保一次只存在一个可变引用)

  • fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
        if self.state.is_some() {
            (*self.state.as_mut().unwrap()).update(ctx, &mut self) <----- NOPE
        } 
        else {
            Ok(())
        }
    }