Compare the Guess

Let's add a few lines to let us compare our guess to a number (that we have hardcoded for now).

main.rs
use std::io;
use std::cmp::Ordering;

fn main() {
    println!("Guess the number!");

    let secret_number = "42".to_string();;

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

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

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

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

The biggest difference is that we introduced Ordering. Ordering is another enum (like Result) that has variants Less, Greater, and Equal. We had to add Ordering because that is the type that cmp returns. Since we are passing in Strings right now, cmp will just compare the strings, so, while we are using numbers, you can really use any string.

cmp is expecting a String, but "52" is type &str. Using to_string() makes a String.

Let's switch that up though and use integers instead!

main.rs
use std::io;
use std::cmp::Ordering;

fn main() {
    println!("Guess the number!");

    let secret_number = 42;

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

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");
        
    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!"),
    }
}r

So what did we add?

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

This code reassigned guess to a u32 which is an unsigned 32-bit number. We'll learn more about various number types later! As you might be able to guess from the previous sections, parse also returns a Result, so we have to make sure to use expect in case of an error. Here's what it looks like now if you try to type in something that is non-numeric:

Last updated