Skip to content

Commit a76ed88

Browse files
committed
tutorial: Add a more detailed example to the intro
1 parent 41bca84 commit a76ed88

File tree

1 file changed

+60
-3
lines changed

1 file changed

+60
-3
lines changed

doc/tutorial.md

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ As a curly-brace language in the tradition of C, C++, and JavaScript,
1717
Rust looks a lot like other languages you may be familiar with.
1818

1919
~~~~
20-
fn fac(n: int) -> int {
20+
fn boring_old_factorial(n: int) -> int {
2121
let mut result = 1, i = 1;
2222
while i <= n {
2323
result *= i;
@@ -36,8 +36,65 @@ tendency towards aggressive abbreviation in the keywords—`fn` for
3636
function, `ret` for return.
3737

3838
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+
~~~~
4198

4299
## Conventions
43100

0 commit comments

Comments
 (0)