How does Rust handle shadowed variables?

只愿长相守 提交于 2021-01-27 13:50:00

问题


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.

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

回答1:


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.

In particular, in your code:

    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

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.

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.



来源:https://stackoverflow.com/questions/57844021/how-does-rust-handle-shadowed-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!