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);
}
By default, all variables in Rust are immutable.
There is no single reason that bindings are immutable by default, but we can think about it through one of Rust's primary focuses: safety. If you forget to say mut , the compiler will catch it, and let you know that you have mutated something you may not have intended to mutate.
Rust actually lets you shadow other variables in a block, so let x: i32 = 565;
is defining a new variable x
that shadows the x
defined earlier with let (x,y) = (1,3);
. Note that you could even have redefined x
to have a different type since the second x
is a whole new variable!
fn main(){
let x = 1;
println!("Now X is {}",x);
let x = "hi";
println!("Now X is {}",x);
}
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:
let iter = vec.into_iter();
let iter = modify(iter);
let iter = double(iter);
Or to make a variable immutable:
let mut x;
// Code where `x` is mutable
let x = x;
// Code where `x` is immutable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With