了解范围和阴影匹配 [英] Understanding scope and shadowing matches

查看:30
本文介绍了了解范围和阴影匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力改进最终的猜谜游戏示例代码 一点.特别是,我打算输出请输入一个数字!"如果用户没有输入数字而不是请输入您的猜测".再次.我正在用一个内循环来做这个.下面的代码确实有效:

I'm trying to improve on the final guessing game sample code a bit. Particularly, I plan to output "Please input a number!" if the user does not input a number rather than "Please input your guess." again. I'm doing this with an inner loop. The code below does work:

let guess: u32;

loop {
    let mut guess_str = String::new();
    io::stdin().read_line(&mut guess_str)
        .ok()
        .expect("Failed to read line");

    guess = match guess_str.trim().parse() {
        Ok(num) => num,
        Err(_) => {
            println!("Please input a number!");
            continue;
        }
    };
    break;
}

如果可以的话,我想通过正确遮蔽匹配来避免 guess_str.如果我将 guess_str 更改为 guess,Rust 会抱怨 使用可能未初始化的变量:`guess`.如果使用上面的代码无法对其进行初始化,我不确定该变量如何可能未初始化.有没有办法只使用 guess 来做到这一点?

I'd like to avoid the guess_str if I can by properly shadowing the matches. If I change guess_str to guess, Rust complains of use of possibly uninitialized variable: `guess`. I'm not sure how the variable could possibly be uninitialized if it's impossible for it to not be uninitialized with the code above. Is there any way to do this only using guess?

推荐答案

我们来看一个更简单的复现:

Let's look at a simpler reproduction:

fn make_guess() -> u32 {
    let guess;

    {
        let mut guess;
        guess = 1;
    }

    guess
}

在这里,您创建一个外部变量 guess,然后将其隐藏在块内.当您将值 1 分配给 guess 时,您将分配给 inner 变量.outer 变量从未设置为任何内容,因此您最终会遇到使用可能未初始化的变量"错误.

Here, you create an outer variable guess and then shadow it inside the block. When you assign the value 1 to guess, you are assigning to the inner variable. The outer variable is never set to anything, thus you end up with the "use of possibly uninitialized variable" error.

有没有办法只使用一个变量

Is there any way to only use one variable

间接地,是的.我会将代码提取到一个函数中.当您成功猜测时,您可以简单地return.否则,您将允许循环发生:

Indirectly, yes. I'd extract the code to a function. When you have a successful guess, you can simply return. Otherwise you allow the loop to occur:

fn make_guess() -> u32 {
    loop {
        let mut guess = String::new();
        io::stdin().read_line(&mut guess)
            .ok()
            .expect("Failed to read line");

        match guess.trim().parse() {
            Ok(num) => return num,
            Err(_) => {
                println!("Please input a number!");
            }
        }
    }
}

这完全避免了阴影,避免了必须使用显式的continue,并为您的代码添加了少量的抽象和组织.

This avoids the shadowing completely, avoids having to use an explicit continue, and adds a small amount of abstraction and organization to your code.

这篇关于了解范围和阴影匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆