Skip to content

Instantly share code, notes, and snippets.

@jroweboy
Forked from steveklabnik/number_game.md
Last active August 29, 2015 14:03
Show Gist options
  • Save jroweboy/369da22de9361598acdd to your computer and use it in GitHub Desktop.
Save jroweboy/369da22de9361598acdd 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
extern crate rand;
// maybe show off that you can put multiple things in a use statement
use std::io::{BufferedReader, stdin};
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = generate_secret_number();
//println!("Secret number is {}", secret_number);
let mut guesses: int = 0;
let mut reader = BufferedReader::new(stdin());
loop {
println!("Please guess a number from 1 to 100 (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, //maybe consider adding an error handling println!("You didn't type an int"); or something
};
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);
}
// usually when I say "Guess a number from 1 to 100" we include 100, so we can show off that the max range is exclusive in Rust
fn generate_secret_number() -> int { std::rng::task_rng().gen_range(1i, 101) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment