Slide 6
Slide 6 text
use std::io::timer::sleep;
!
// Rust 0.10
fn main() {
let actions = [("Captain America", "bashes", 20),
("Black Widow", "slashes", 25),
("Ironman", "throws cash at", 0),
("Hulk", "SMASHES", 200)];
!
let mut outcomes =
actions.iter()
.map(|&action| {
let (hero, attack, damage) = action;
format!("{:s} {:s} Red Skull for {:d} damage",
hero, attack, damage)
});
!
for outcome in outcomes {
spawn(proc() {
sleep(500);
println!(“{:s}”, outcome);
});
}
}
Rust sample
Lets take a look at a little sample as a taster…
!
In this scenario the Avengers have just rolled for initiative in a battle against Red Skull we want to show the results.
!
The actions are declared in the form of a vector of tuples. Rust calls arrays “vectors”, much like C++. Each tuple is made up of a hero string, an attack
string and an integer value giving damage.
!
Next we need to figure out the outcome of each action to output. We iterate though each action tuple transforming the tuple into a string using the map()
method. Ruby developers will notice the inside of map() looks similar to a Ruby block. This is called a closure in Rust. Inside the closure we’ll decode the
tuple contents to hero, attack and damage variables. format!() will create a sanitized string output replacing the {:s}, {:s} and {:d} with hero, attack and
damage.
!
Finally in the for loop at the end we’ll iterate through each outcome string and display it. We’re wrapping the println!() statement in a spawn() block to
make each output happen asynchronously in it’s own lightweight thread. Rust is really good at concurrency and multithreading, we’ll talk about that later.
The sleep() statement helps induce the 4 outcomes to display in random order.