Rust let is a point of failure

Today, I encountered a problem when writing code. An encapsulated function processes logic, but the function is cyclic outside, and there is a let mut hashmap definition inside the function. This causes the hashmap to be reinitialized every time it is looped, causing deviations from expectations. As a result, I think that let should not allow variable shadowing. For example, go's var, Typescript/JavaScript's let, and const all do not allow variable shadowing. Why is rust like this?

Can you give a code example of the issue you encountered? It's hard to tell by just your description.

Unityped dynamic languages are completely different when it comes to how scoping works, so that comparison is not useful.

Rust has a compiler to give you "hey, you never edited that outer one" warnings, and you can't do things like x = x.to_string(); in rust -- the way you can in JS that doesn't care -- so shadowing is useful in Rust in a way it isn't in JS.

5 Likes

Clippy has lints for shadowing, the most useful one being the clippy::shadow_unrelated lint, which prevents accidental shadowing, while allowing idiomatic shadowing patterns.

2 Likes

Please remove the "Unsafe Code Guidelines" tag from this thread, it has nothing to do with the UCG.

1 Like