Reputation: 161
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;
}
};
}
}
Upvotes: 5
Views: 1211
Reputation: 98358
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.
Upvotes: 5