Reinitialized variable binding [Solved]


Hi all, I am new to both Rust and programming. I am wondering why rust allow us to reinitialized a variable, also without throwing any notice. How if we accidentally reinitialized it, and giving semantic error. Why dont use special annotation like “let reinit varname” to reinitial & avoid it. What is the benefit of reinitilized variable?. Thank you.


There’s no such thing as reinitializing in Rust, what you’re actually referring to is shadowing. Basically what happens is that if a variable name is reused the previous one is no longer accessible. When non-lexical lifetimes are implemented I imagine it’ll be dropped at that point in the code, but right now I believe the variable’s lifetime is still until the end of the current block.

This question comes up every so often as to why there’s no warning, and the general answer is because it’s encouraged to help with good variable names. Variables sometimes have small transformations where they change type but they represent the same other languages you’d have to give all the variables different names or play games with blocks to limit their scope; in Rust you can just shadow the variable!

And because the compiler is able to type check so much, I think there ends up being very little risk in practice with this feature, which is why it made it past 1.0.


Right, the right term is shadowing and it turns out just like a regular mutable binding with subtle differences. Thank you for point that out. I am sorry for asking silly basic question that easily found in the documentation, but your explanation is helping me .:sweat_smile:


Hopefully not! It’s important for the soundness of examples like

let s = String::from("foo");
let s = &s;

which is a major use-case for shadowing.


Please do not apologize for asking questions. One day all the silly basic questions will be easy to find on google, but that only happens by people asking them in public many different ways. You have contributed one small layer to the sedimentary rock that is good documentation.


Thanks for All, for the enlighten responses.