Skip to content

Instantly share code, notes, and snippets.

@toolness
Created March 15, 2015 16:31
Show Gist options
  • Save toolness/f9eb67af10ccbfd01510 to your computer and use it in GitHub Desktop.
Save toolness/f9eb67af10ccbfd01510 to your computer and use it in GitHub Desktop.
Guess The Number in Rust
#![feature(old_io)]
#![feature(rand)]
#![allow(deprecated)]
use std::cmp::Ordering;
use std::old_io;
use std::rand;
fn cmp(a: u8, b: u8) -> Ordering {
if a > b {
Ordering::Greater
} else if a < b {
Ordering::Less
} else {
Ordering::Equal
}
}
fn main() {
let random_num = rand::random::<u8>();
let mut attempts = 0;
println!("I am thinking of a random 8-bit integer between 0 and 255.");
println!("Can you guess it?");
loop {
let input = old_io::stdin()
.read_line()
.ok()
.expect("Failed to read input!");
match input.trim().parse::<u8>() {
Ok(guess) => {
attempts += 1;
match cmp(guess, random_num) {
Ordering::Greater => {
println!("Your guess is too big!");
},
Ordering::Less => {
println!("Your guess is too small!");
},
Ordering::Equal => {
if attempts == 1 {
println!("You got the number on your first try!");
println!("Were you debugging my process or something?");
} else {
println!("You got the number after {} tries!", attempts);
}
break;
}
}
},
Err(_) => {
println!("That doesn't look like much of a number to me.");
}
}
}
}
@toolness
Copy link
Author

I wrote this after going through most of the first chapter of The Rust Programming Language book. The final section of the chapter involves writing a number guessing game and I decided to try writing it myself before reading the section.

The chapter currently uses old_io without explaining why--it looks like the language is going through a bit of redesign as it prepares for its 1.0 release.

I had to do a bit of web searching to find out how to generate random numbers and convert strings to integers, which the chapter hadn't taught me yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment