Mutates w/o mut keyword

-----@Asus:~/Devel/rust/book/var_test$ cat src/var_test.rs

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"

This is not mutation. The second x is a distinct variable. Google "shadowing".

OK - the 'let' keyword causes shadowing - thanks.

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

Thanks - Is it possible to prevent shadowing - without using const?

Is it possible to prevent shadowing

When your question is “how can I stop using part of the language features”, the place you should look for help is Clippy's restriction lints. There are a few for different sorts of shadowing:

#![deny(clippy::shadow_reuse)]
#![deny(clippy::shadow_same)]
#![deny(clippy::shadow_unrelated)]

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

let x = 50;
...
let x = 50;

but allows

let x = x + 10;

since that is clearly doing something on purpose.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.