Numpty
Numpty

Reputation: 1481

Rust basic while loop

(Hopefully) A simple question from a complete rust beginner. What's wrong with my loop?

num evaluates to '69' rather quickly, but the loop never exits once num is set to '69'. I'm missing something obvious I'm sure...

extern crate rand;

use rand::Rng;

fn main() {
    let funny_number: u16 = 69;
    let mut num: u16 = 0;
    let mut rng = rand::thread_rng();

    while num != funny_number {
        let mut num: u16 = rng.gen_range(0, 100);
        println!("{}", num);
    }
}

Upvotes: 2

Views: 163

Answers (1)

stud3nt
stud3nt

Reputation: 2128

The problem is that you are creating a new variable inside while loop which has a different scope and the num in while condition never changes. Due to which it goes into an infinite loop. Try with the below code:

extern crate rand;

use rand::Rng;

fn main() {
    let funny_number: u16 = 69;
    let mut num: u16 = 0;
    let mut rng = rand::thread_rng();

    while num != funny_number {
        num = rng.gen_range(0, 100);
        println!("{}", num);
    }
}

Upvotes: 6

Related Questions