Skip to content

Instantly share code, notes, and snippets.

@quux00
Last active January 2, 2016 23:49
Show Gist options
  • Save quux00/8379084 to your computer and use it in GitHub Desktop.
Save quux00/8379084 to your computer and use it in GitHub Desktop.
Learning Rust traits ... poorly
fn main() {
let mut mon1: ~Sleestak = ~Monster::new();
let mut mon2: ~Reaver = ~Monster::new();
let mut monsters = [mon1 as ~Monster, mon2 as ~Monster];
println!("{:?}", monsters);
println("------------------------------");
// attempt 1: fail
for m in monsters.iter() {
m.attack(22u); // ERROR: cannot borrow immutable dereference of ~ pointer as mutable
println!("{:?}", m);
}
// attempt 2: fail
for m in monsters.iter() {
let mut mm = m;
mm.attack(22u); // ERROR: cannot borrow immutable dereference of ~ pointer as mutable
println!("{:?}", mm);
}
// attempt 3: fail
for m in monsters.iter() {
let mut mmm = &mut m; // error: cannot borrow immutable local variable as mutable
mmm.attack(22u);
println!("{:?}", mmm);
}
}
trait Monster {
fn new() -> Self;
fn attack(&mut self, strength: uint);
}
struct Reaver {
attack_strength: uint,
health: uint
}
struct Sleestak {
attack_strength: uint,
health: uint
}
impl Monster for Reaver {
fn new() -> Reaver {
Reaver{attack_strength: 50, health: 100}
}
fn attack(&mut self, strength: uint) {
if strength > self.health {
self.health = 0;
} else {
self.health = self.health - strength;
}
}
}
impl Monster for Sleestak {
fn new() -> Sleestak {
Sleestak{attack_strength: 22, health: 100}
}
fn attack(&mut self, strength: uint) {
if strength > self.health {
self.health = 0;
} else {
self.health = self.health - strength;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment