I have the following Rust program and I expect it to result in an compilation error since x
is reassigned later. But it complies and gives output. Why?
fn main() {
let (x, y) = (1, 3);
println!("X is {} and Y is {}", x, y);
let x: i32 = 565;
println!("Now X is {}", x);
}
Rust actually lets you shadow other variables in a block, so
let x: i32 = 565;
is defining a new variablex
that shadows thex
defined earlier withlet (x,y) = (1,3);
. Note that you could even have redefinedx
to have a different type since the secondx
is a whole new variable!This reddit thread goes into more detail about why this is useful. The two things that are mentioned that seem interesting are:
For operations which take ownership of the variable, but return another variable of the same type, it sometimes "looks nice" to redefine the returned variable to have the same name. From here:
Or to make a variable immutable: