@@ -17,7 +17,7 @@ As a curly-brace language in the tradition of C, C++, and JavaScript,
17
17
Rust looks a lot like other languages you may be familiar with.
18
18
19
19
~~~~
20
- fn fac (n: int) -> int {
20
+ fn boring_old_factorial (n: int) -> int {
21
21
let mut result = 1, i = 1;
22
22
while i <= n {
23
23
result *= i;
@@ -36,8 +36,65 @@ tendency towards aggressive abbreviation in the keywords—`fn` for
36
36
function, ` ret ` for return.
37
37
38
38
You should, however, not conclude that Rust is simply an evolution of
39
- C. As will become clear in the rest of this tutorial, it goes in
40
- quite a different direction.
39
+ C. As will become clear in the rest of this tutorial, it goes in quite
40
+ a different direction, with efficient, strongly-typed and memory-safe
41
+ support for many high-level idioms.
42
+
43
+ Here's a parallel game of rock, paper, scissors to whet your appetite.
44
+
45
+ ~~~~
46
+ use std;
47
+
48
+ import comm::{listen, methods};
49
+ import task::spawn;
50
+ import iter::repeat;
51
+ import std::rand::{seeded_rng, seed};
52
+ import uint::range;
53
+ import io::println;
54
+
55
+ fn main() {
56
+ // Open a channel for receiving game results
57
+ do listen |result_from_game| {
58
+
59
+ let times = 10;
60
+ let player1 = "graydon";
61
+ let player2 = "patrick";
62
+
63
+ for repeat(times) {
64
+ // Start another task to play the game
65
+ do spawn |copy player1, copy player2| {
66
+ let outcome = play_game(player1, player2);
67
+ result_from_game.send(outcome);
68
+ }
69
+ }
70
+
71
+ // Report the results as the games complete
72
+ for range(0, times) |round| {
73
+ let winner = result_from_game.recv();
74
+ println(#fmt("%s wins round #%u", winner, round));
75
+ }
76
+
77
+ fn play_game(player1: str, player2: str) -> str {
78
+
79
+ // Our rock/paper/scissors types
80
+ enum gesture {
81
+ rock, paper, scissors
82
+ }
83
+
84
+ let rng = seeded_rng(seed());
85
+ // A small inline function for picking an RPS gesture
86
+ let pick = || [rock, paper, scissors][rng.gen_uint() % 3];
87
+
88
+ // Pick two gestures and decide the result
89
+ alt (pick(), pick()) {
90
+ (rock, scissors) | (paper, rock) | (scissors, paper) { copy player1 }
91
+ (scissors, rock) | (rock, paper) | (paper, scissors) { copy player2 }
92
+ _ { "tie" }
93
+ }
94
+ }
95
+ }
96
+ }
97
+ ~~~~
41
98
42
99
## Conventions
43
100
0 commit comments