Trying to get my program to work

Heres my code:

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

fn main() {
    let number = rand::rng().random_range(0..=1292929);
    let mut guess = String::new();
    
    println!("guess the number");
    
    loop {
        io::stdin().read_line(&mut guess).expect("AAAAAAAAAHH");
        
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };
        
        println!("you guessed THIS {number}");
        
        match guess.cmp(&number) {
            Ordering::Greater => println!("TOO BIG"),
            Ordering::Less => println!("TOO SMALL"),
            Ordering::Equal => {
                println!("YOU WIN!!");
                break;
            }
        }
        
    }
    
}

When i run it it works, i enter a number and it comes up with the right stuff but then when i go to guess another number nothing happens, its meant to go back to the start of the loop

Is this spam or does the snippet come from an online tutorial or something?[1] I answered a question with almost the exact same code three months ago:


  1. See answers below, I wasn't aware of the guessing game chapter of the Rust book ↩︎

2 Likes

Oh its from the rust book since im learning rust for the first time

1 Like

To fix the code, either declare a new let mut guess = String::new() in each iteration of the loop, or write guess.clear() at the beginning of the loop to make sure the input is read into an empty buffer.

(jofas explains how using the same buffer doesn’t work in his linked post)

2 Likes

Thanks i firgot to put the guess variable in the loop oops

You don't need to do that. You just need to clear it at the beginning (or the end) of each loop.

It's better to use unwrap/expect, as well as asserting your expectations, instead of silent errors, because you can get quick feedback and pinpoint the issue. It would've probably helped there too.