Skip to content

Instantly share code, notes, and snippets.

@Ryman
Forked from steveklabnik/number_game.md
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save Ryman/a45df03b8115d5fe4bae to your computer and use it in GitHub Desktop.

Select an option

Save Ryman/a45df03b8115d5fe4bae to your computer and use it in GitHub Desktop.

Help the docs!

So! The new tutorial will be focused on building several small projects in Rust. This example is the first one: a classic 'guessing game.' This was one of the first programs I wrote when I first learned C. 😄

I'd like the feedback of the community before I actually start writing the guide. So this code will be the final code of the first real example Rust programmers see. So I want it to be good. I don't claim this code is good, I just worked something out real quick.

The idea is that I will slowly build from hello world to this final code in steps, introducing one concept at a time. Here are the concepts I'd like a Rust programmer to understand by the time they're done:

Concepts

  • If
  • Functions
    • return (wrt semicolons)
  • comments
  • Testing
  • attributes
  • stability markers
  • Crates and Modules
  • visibility
  • Compound Data Types
  • Tuples
  • Structs
  • Enums
  • Match
  • Looping
  • for
  • while
  • loop
  • break/continue
  • iterators
use std::io;
use std::rang;
use std::rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = generate_secret_number();
//println!("Secret number is {}", secret_number);
let mut guesses: uint = 0u;
let mut reader = io::stdin();
loop {
println!("Please input guess #{}", guesses + 1);
let input = reader.read_line().unwrap();
let input_num = from_str::<int>(input.as_slice().trim_right());
let num = match input_num {
Some(num) => num,
None => continue,
};
println!("You guessed: {}", num);
guesses += 1;
match num.cmp(&secret_number) {
Less => println!("Too small!"),
Greater => println!("Too big!"),
Equal => {
println!("You win!");
break;
},
}
}
println!("You took {} guesses!", guesses);
}
fn generate_secret_number() -> int { rand::task_rng().gen_range(1i, 100) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment