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