Rust 如何处理阴影变量? [英] How does Rust handle shadowed variables?

查看:58
本文介绍了Rust 如何处理阴影变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很强的 C/C++ 背景,最近正在学习 Rust.对 Rust 如何处理阴影变量感到困惑.特别是,我期望下面的代码段运行没有问题,因为 guess 在下一次被称为 read_line 中的字符串之前从一个字符串阴影到一个整数.

I have strong C/C++ background and am learning Rust these days. Got puzzled by how Rust handles shadowing variables. Particularly, I was expecting that the following code segment shall run without problem because guess is shadowed from a String to an integer before the next time it is called as a String in read_line.

阅读 API 文档后,我了解到 read_line 会将下一个输入附加到 guess.但是在阴影之后, guess 是否应该被视为一个整数并且这样的附加是无效的?请帮忙.

Reading the API document, I understand read_line would append the next input to guess. But after the shadowing, should guess be considered as an integer and such appending be invalid? Please help.

fn main() {
    let secret_number = 10;
    let mut guess = String::new();

    loop {
        //guess.clear(); // uncomment this line will make it work. 
        println!("Please input your guess:");
        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read guess.");
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };
        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        };
    }
}

推荐答案

阴影是一种纯粹的句法现象.它对生成的代码没有影响,也就是说,如果为每个变量选择不同的名称,生成的代码将是相同的.只是影子变量不能通过名称引用.

Shadowing is a purely syntactic phenomenon. It has no effect in the generated code, that is the generated code would be identical if you chose a different name for each variable. It is just that the shadowed variable cannot be referenced by name.

特别是在您的代码中:

    let mut guess = String::new(); //1
    ...    
    loop {
        io::stdin().read_line(&mut guess)... //2
        let guess: u32 =  match guess.trim()... ; //3
        match guess.cmp(...) // 4
    }
    //5

第2行和第3行的用法指的是第1行声明的变量,第4行的用法指的是第3行的声明.变量的类型没有变化,变量的类型也没有任何变化一生.简单地说,它们是两个碰巧具有相同名称的不同变量,因此您的程序将无法访问第 4 行和第 1 行中的变量.

The usages in line 2 and 3 refer to the declared variable in line 1, while the usage in line 4 refers to the declaration in line 3. There is no change in the type of the variable, nor there is any change in lifetimes. Simply they are two different variables that happen to have the same name, so that it will be impossible for your program to access the variable in line 1 from line 4.

事实上,在循环结束后,在第 5 行,名称 guess 将再次引用第 1 行中的变量,因为另一个超出了作用域.

In fact, after the loop finises, in line 5, the name guess will again refer to the variable in line 1, because the other one went out of scope.

这篇关于Rust 如何处理阴影变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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