fn main() {
let x = 50;
println!("x = {}", x);
let x = 60;
println!("x = {}", x);
}
-----@Asus:~/Devel/rust/book/var_test$ touch src/var_test.rs
-----@Asus:~/Devel/rust/book/var_test$ cargo build
Compiling var_test v0.1.0 (/home/rajag/.mnts/devel/rust/book/var_test)
Finished dev [unoptimized + debuginfo] target(s) in 0.34s
-----@Asus:~/Devel/rust/book/var_test$ target/debug/var_test
x = 50
x = 60
-----@Asus:~/Devel/rust/book/var_test$
Previously, on a different copy of the project, I had changed the second assignment to let mut x = 60;
which threw a warning and advise to run cargo fix --allow-dirty --bin "variables"
If you’re asking why it’s possible to mutate the variable x, it’s because you’re not mutating it but shadowing it. The second declaration happens to be an integer as well, but in Rust you can shadow the previous declaration with any new type you wanted. Scope and Shadowing - Rust By Example
Or choose one of the other lint levels instead of deny. Then, run cargo clippy and observe the error. (You can run Clippy in a CI system to reject changes that would include shadowing.)
However, I suggest that you do not do this. Use of shadowing is a standard part of idiomatic Rust. At most, activate deny(clippy::shadow_unrelated) which rejects shadowing that isn't related to the original; that is, it rejects