簡體   English   中英

參考和壽命

[英]References and lifetimes

我剛剛開始對Rust進行實驗,並希望將這個簡單的C ++程序轉換為Rust:

#include <iostream>
#include <vector>
#include <stdint.h>

using namespace std;

struct Game;

struct Player {
  Player(Game* game, uint32_t health) : game(game), health(health) {
  }

  uint32_t health;
  Game* game;
};

struct Game {
  Player& new_player() {
    players.emplace_back(this, 100);
    return players.back();
  }

  vector<Player> players;
};


int main() {
  Game g;
  g.new_player().health -= 10;
  g.new_player().health -= 20;

  for (auto p : g.players) {
    cout << "player health = " << p.health << endl;
  }

  return 0;
}

這是我頑強的Rust嘗試:

struct Player<'a> {
  health: i32,
  game: &'a mut Game<'a>
}

struct Game<'a> {
  players: Vec<Player<'a>>
}

impl <'a> Game<'a> {
  fn new() -> Game<'a> {
    Game { players: Vec::new() }
  }

  fn new_player(&'a mut self) -> &'a mut Player<'a> {
    unsafe {
      // Ugly unsafe hack to fix compiler error
      let ps: *mut Game<'a> = self;
      self.players.push(Player { health: 100, game: &mut *ps });
      self.players.mut_last().unwrap()
    }
  }
}

fn main() {
  let mut g = Game::new();
  g.new_player().health -= 10;

  // Compiler error about multiple borrows
  g.new_player().health -= 20;

  // Compiler error about multiple borrows
  for p in g.players.mut_iter() {
    println!("player health = {}", p.health);
  }
}

但是,我使用了不安全的代碼(希望這不是必需的),並且遇到了引用和生命周期的問題,而這些問題我真的不知道如何解決。 用Rust編寫此代碼的慣用方式是什么? 還是Rust類型系統目前過於局限,無法以安全的方式進行表達?

順便說一句,我正在使用“ rustc 0.12.0-pre-nightly(6bb72600c 2014-08-05 00:01:28 +0000)”。

聽起來對一個對象有多個可變的引用是不可行的,但是這是在不安全的代碼中引起的。 這是一個等待發生的內存安全錯誤,因為您已經打破了關於可變引用的不變性。

如果您希望能夠從多個位置訪問它,則需要使用Rc < RefCell <Game>> (將Player內部的一個設置為Weak<RefCell<Game>> ),並且仍然需要以確保在運行時不會一次對基礎Game進行兩個可變的引用。

如果您可以避免在Player存儲對Game的引用,那也可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM