« Back to Index

Rust: Book Examples

View original Gist on GitHub

Tags: #rust #rng

1. Guessing Game.rs

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    let secret_number = rand::thread_rng().gen_range(1, 101);

    println!("secret number: {}", secret_number);

    loop {
        println!("input a guess...");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("failed to read input");

        let guess: u32 = guess.trim().parse().expect("please type a number");

        println!("you guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("too small"),
            Ordering::Greater => println!("too big"),
            Ordering::Equal => {
                println!("you win");
                break;
            }
        }
    }
}