简体   繁体   English

Rust 基本的 while 循环

[英]Rust basic while loop

(Hopefully) A simple question from a complete rust beginner. (希望如此)来自一个完整的 Rust 初学者的一个简单问题。 What's wrong with my loop?我的循环有什么问题?

num evaluates to '69' rather quickly, but the loop never exits once num is set to '69'. num计算结果为 '69' 相当快,但是一旦num设置为 '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.问题是您在 while 循环中创建了一个新变量,该变量具有不同的范围,而 while 条件中的 num 永远不会改变。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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