简体   繁体   中英

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);
    }
}

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM