Skip to content

Instantly share code, notes, and snippets.

@pzol
Last active August 29, 2015 14:12
Show Gist options
  • Save pzol/8c6b8ed84fefaffe5b22 to your computer and use it in GitHub Desktop.
Save pzol/8c6b8ed84fefaffe5b22 to your computer and use it in GitHub Desktop.
extern crate core;
use core::cell::Cell;
#[deriving(Copy, Show)]
struct Pos(u32, u32);
#[deriving(Show)]
struct Monster {
name: String,
pos: Cell<Pos>
}
impl Monster {
pub fn goto(&self, pos: Pos) {
self.pos.set(pos);
}
}
struct Game {
monsters: Vec<Monster>
}
impl Game {
pub fn new() -> Game {
Game { monsters: vec![] }
}
pub fn add_monster(&mut self, monster: Monster) {
self.monsters.push(monster)
}
#[allow(unused_variables)]
fn can_goto(&self, pos: Pos) -> bool {
true
}
pub fn update(&self) {
for monster in self.monsters.iter() {
let Pos(x, y) = monster.pos.get();
let dst = Pos(x + 1, y + 1);
if self.can_goto(dst) {
monster.goto(dst)
}
}
}
// pub fn update(&mut self) {
// let game : &Game = unsafe { ::std::mem::transmute_copy(&self) };
// for monster in self.monsters.iter_mut() {
// let (x, y) : (uint, uint) = (monster.x + 1, monster.y + 1);
// if game.can_goto(x, y) {
// monster.goto(x, y)
// }
// }
// }
}
fn main() {
let mut game = Game::new();
game.add_monster(Monster { name: "Sauron".to_string(), pos : Cell::new(Pos(0,1))});
game.add_monster(Monster { name: "Morgoth".to_string(), pos: Cell::new(Pos(40, 40)) } );
game.update();
}
@pzol
Copy link
Author

pzol commented Jan 3, 2015

/Users/pzol/Dropbox/src/rust/rogue/test/bc1.rs:36:16: 36:20 error: cannot borrow *self as immutable because self.monsters is also borrowed as mutable
/Users/pzol/Dropbox/src/rust/rogue/test/bc1.rs:36 if self.can_goto(x, y) {
^~~~
/Users/pzol/Dropbox/src/rust/rogue/test/bc1.rs:34:24: 34:37 note: previous borrow of self.monsters occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of self.monsters until the borrow ends
/Users/pzol/Dropbox/src/rust/rogue/test/bc1.rs:34 for monster in self.monsters.iter_mut() {
^~~~~~~~~~~~~
/Users/pzol/Dropbox/src/rust/rogue/test/bc1.rs:40:6: 40:6 note: previous borrow ends here
/Users/pzol/Dropbox/src/rust/rogue/test/bc1.rs:34 for monster in self.monsters.iter_mut() {
...
/Users/pzol/Dropbox/src/rust/rogue/test/bc1.rs:40 }
^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment