Compiler Error Scavenger Hunt

This activity is designed to teaching you to to not fear compiler errors and to show you that Rust's error messages are actually quite helpful once you learn to read them!

Please do NOT use VSCode yet! Open your files in nano, TextEdit / Notepad or another plain text editor.

Instructions

The code contains a complete guessing game (it's okay if you don't know how it all works yet!)

Working in pairs, see how many different compiler errors you can create.

I'll give you a 2 minute warning to wrap up in gradescope.

Again Please do NOT use VSCode yet! It ruins the fun

Rules:

  1. Create a new project in your project folder with cargo new guessing_game
  2. Copy the starter code into src/main.rs, and add the rand dependency to the Cargo.toml file
  3. Make one change at a time that breaks compilation (try misspelling, removing, reordering)
  4. Run cargo check or cargo build to see the error
  5. Record the error message - write down in the gradescope assignment what you changed and what kind of error it produced
  6. Undo your change and try a different way to break it
  7. Goal: Find at least 8 different error types (I found 14, as a class can we find more?)!

Add to the Cargo.toml file:

Under [dependencies]:

rand = "0.8.5"

Starter Code (src/main.rs)

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

fn main() {
    println!("Guess the number!");
    
    let secret_number = rand::thread_rng().gen_range(1..=100);
    let mut attempts = 0;
    
    loop {
        println!("Please input your guess:");
        
        let mut guess = String::new();
        
        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");
            
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Please enter a valid number!");
                continue;
            }
        };
        
        attempts += 1;
        
        println!("You guessed: {}", guess);
        
        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win! It took you {} attempts.", attempts);
                break;
            }
        }
    }
    
    let final_message = format!("Thanks for playing! You made {} guesses.", attempts);
    println!("{}", final_message);
}

Debrief Questions:

  • Let's make a list together - how many did we find?

  • Which error was the most confusing?

  • Which error message was the most helpful?

  • Did any errors surprise you?

  • What patterns did you notice in how Rust reports errors?