Programming a Guessing Game1
To run the program:
$ cargo run --bin guessing-game
Compiling guessing-game v0.1.0 ...
-
Sometimes (
extern crate rand
) you just need stack overflow. -
A
String
is both an immutable and mutable buffer of characters. -
You create a new mutable variable with
let mut
:let mut guess = String::new();
-
And read into it as a reference, i.e.
&mut guess
:io::stdin().read_line(&mut guess);
-
Many Rust APIs return enums, such as
Result
. You can use.expect
to panic:result.expect("Failed to read line");
-
Or (pattern)
match
against the result, such as:let guess:u32 = match guess.parse() { Ok(num) => num, Err(_) => { println!("Invalid!"); continue; } }