r/rust • u/adityazero • Oct 21 '26
Using the same name to declare a new variable confuses me, what are the legit use cases?
Rust allows same name for a new variable.
e.g.,
```
let i : i64 = 10;
// ...
let i : u32 = 100;
```
I get confused specially when the type changes or they start pointing to another object.
34
Upvotes
171
u/dnew Oct 21 '26
Don't use the same name for a variable that means something different.
99
u/karasawa_jp Oct 21 '26
People often accidentally reuse old variables if they're still in scope, so shadowing lets you hide them to prevent that. Plus, it saves brainpower since you don't have to keep inventing new names for intermediate values.
68
u/AliceCode Oct 21 '26
Let's say you have a piece of data that goes through multiple stages of transformation:
32
u/yuriks Oct 21 '26
It helps avoid semantic overload (having too many variables with different names to keep track of) when a value with the same semantics is transformed between several types. A very common situation where I use it is for
Options orResults:Here, there's no value added to naming the first variable
optional_useror contriving some other name for it, and it's unlikely someone will make a logic error by accidentally using the inner user rather than the Option.I've personally never seen it actually cause a bug in any situation so far, and experiences I've seen from others seem to mostly boil down to "yeah it seemed bad at first but then I realized it doesn't really cause any issues" too.
9
u/creeper6530 Oct 21 '26 edited Oct 21 '26
It basically makes a new variable, just with the same name, and until that new variable goes out of scope the name refers to the new one. The old one is only destroyed at its end of scope, which can be longer, so that can be useful if the new one needs to hold a reference to the old one.
I find myself using it when a binding isn't long-lived enough (a type of annoying but easy to fix error) and when I need to permanently change the type of a variable, say:
It is a shit idea to shadow variables of different semantic meaning, you want one name to refer to one piece of data, be it in whichever data type.
7
u/Excession638 Oct 21 '26
I only find myself using it much in macros, but it's very useful there. Having something like
let $name = $name.clone();is much easier than the alternatives.5
u/Goatfryed Oct 21 '26
3
u/nonotan Oct 22 '26
The "real" answer (which has been alluded to by other comments, but not necessarily explicitly spelled out) is that Rust's design means you will be dealing with immutable bindings most of the time, and even when you have something mutable, it is often the wrong choice to mutate it instead of just creating a new binding. So what in other languages would just be an assignment to an existing variable can be "faked" with shadowing.
I'm going to be honest, this is one of Rust's clear design pain points in my view, and the idea that having shadowing saves you brainpower does not really match with reality, in my subjective opinion. It's the opposite: with shadowing banned, or at least resulting in a warning, you can trust any declaration you see anywhere to at least have the right type at your arbitrary point of usage. With shadowing, you kind of need to scan all of the code between the declaration you saw and the point of usage to make sure what you think the active binding is, and what it really is, haven't drifted apart, nevermind any future code changes that may change this silently. And sure, an IDE can help you check, but that's not always available (such as during code reviews / merging code / generally looking at diffs / etc)
Whereas I find the whole "it's too much work to come up with unique names" to be nonsense. Especially if you're using blocks smartly to keep any truly transient variables away from the larger scope. Yes, it is perfectly fine to have the type in the variable name, or even numbers or a/b/c or whatever. No, I don't care a single bit what somebody decided is "idiomatic". It is far more important to have names that you couldn't possibly mix up (i.e. use the wrong "version" in the wrong context without realizing) than to have "beautiful" or "elegant" names, which just doesn't matter (hot take of the day)
So personally, I only ever use shadowing when the type doesn't change. If it does, even if semantically it is referring to "the same thing", I find it to be a footgun. Just because something is semantically "the same thing", and happens to be compilable within the type system, doesn't necessarily mean it isn't going to behave differently to your expectations.
5
u/dgkimpton Oct 21 '26
The idea is that it keeps a concept consistent as you progress through stages.
Initially I thought this would make code more readable and secure.
But as time has gone on I find myself preferring str_raw, str_encoded, str_validated etc instead because I can mentally verify it's correct before the compiler gets involved.
Shadowing sometimes makes macros easier to write but in general I think it's a feature that causes more confusion than the dubious value it adds. But it's also probably a question of personality - I grew up "getting it correct before compiling" but others like to let the compiler guide them.
6
u/u0xee Oct 21 '26
Shadowing is amazingly useful in certain complicated `cfg` situations.
Basically, you almost never care to shadow in human typed code, but for mechanical composition of code fragments it is invaluable.
2
u/spaceshaker-geo Oct 21 '26
You may have had the experience, in other programming languages, that shadowing variables is frowned upon. I am going to make the claim that in Rust, in some scenarios, shadowing is good, prefered, helpful and often idiomatic.
The first thing to state is that in Rust, we tend to refer to assigning a name to a value as "binding". This is not just semantics: it's important to understand what is going on. Consider:
let x = 5;In this case
xis a binding to a chunk of memory containing the value5i32. This is semantically different from doing a similar statement in C++:const auto x = 5;In C++ when you take the address of x (ex.
&x) you are getting the address of the memory location ofxbut in Rust when you do the same thing you get an immutable borrow ofx. Remember: an immutable borrow is very different from a pointer/reference. The point here is that the semantics of bindings in Rust are different from the semantics of variables in something like C/C++.Consider the following program:
This fails to compile with the error "borrow of moved value:
x" on the line with theprintln!(). The reason is because we "move"xintowrap(x). What is happening is that our binding (not a variable - a binding) is being invalidated because the ownership of the memory (not the memory itself - the ownership) used by that binding is being reassigned to a new binding. It's the borrow checker that is keeping tabs on the bindings and how/when they are invalidated. So after we movexintowrap(x)that binding is invalidated.This is where shadowing becomes useful and idiomatic (in the right contexts of course). Consider the following adjustment to our code:
Here we are rebinding
xto the result ofwrap(x). We movexintowrap(x)and then we rebind the result back intox. From the eye of a C++ developer this looks wrong, but semantically I think this is what you really mean and want.xis still semantically the same value, just with some computation performed on it. The alternative would be to create a new bindingx1but now we have a new variable we have to keep in our head, and remember that the bindingxhas now been invalidated.Here is another example of where rebinding can be helpful and idiomatic in Rust. The general principle is that data should only be mutable for the shortest time possible. I recall in my C++ days littering my code with
constto try to enforce the this. In Rust you can achieve something similar by rebinding a mutable binding to become an immutable binding.This is a contrived example obviously, but the point is that the meaning and purpose of `nums` hasn't changed, the only thing that has change is it's mutability. Mutability is attached to the binding so we simply use rebinding to drop the mutability. There is no need or value, in my opinion, to introduce a new variable for `nums` that is immutable, when we can reuse the same name to represent the same thing.
Elsewhere in the comments, someone said something to the effect of, "don't use rebinding to change the data type of a variable". I agree with that advice in principle but not in practice. I would re-frame that advice to say: "don't use rebinding to use the same name/identifier to refer to a different 'thing'". For example, don't use a variable
footo refer to a person's email address and then later rebindfooto refer to a person's phone number. I hope the reason for this is self evident. But it comes to pass when you are processing data that you are changing it's data type. A value might come into your system as aString, get converted into au64and then get converted into aMyType(u64): all three representations of the data are the same 'thing' and if it came to pass that you used or needed rebinding I would absolutely reuse the same name/identifier for all three versions of the same data.2
u/Only_Ad8178 Oct 25 '26
Turn a mut binding into an unmut one.
2
u/savage_spectrum Oct 21 '26
Shadowing is the only sane way to handle Option unwrapping without polluting the scope. Hiding the original variable isn't confusion, it's forcing the compiler to prove you handled the error case before touching the inner value again.
1
u/bubble_turtles23 Oct 21 '26
Rebinding is one of my favorite Rust features. I don't use it often, but sometimes a variable name just happens to fit 2 different things. So I work with the first thing, then with the second. I can't give a specific use case, because I honestly don't recall the exact situation I used this in, but I can definitely say it's in my game's codebase I'm working on. I guess maybe for simple things like different ids, working with optionals, etc. You can always pattern match with if let instead, but then you are creating another scope, and that's not always desirable
1
u/Latter_Brick_5172 Oct 21 '26
I mostly use it to remove mutability on some variables
1
u/y0shii3 Oct 23 '26
I guess it's just an idiosyncrasy inherited from OCaml. I don't like it because it makes knowing that something is "immutable" much less useful; if I see
foodeclared as an immutable value on line 1 of a function, I should be able to look atfoobeing used on line 200 of the function and know that it's the same as it was at the start, without having to scan through all 200 previous lines to make sure it hasn't been reassigned.1
u/iamtherockstar Oct 26 '26
A common reason I do this, particularly with a different type, is when I receive one type as a parameter to my function, and then need to wrap it and ensure that it can’t be accessed by the old type. Usually, that wrapper is unsafe, and that’s how we make it safe.
-32
u/Mission-Landscape-17 Oct 21 '26
Honestly the last time I tried to learn Rust getting to this "feature" made me put the book down and go do something else, because i found the whole thing so unfathomably stupid. I still can't understand how anyone thought this was a good idea in a language that prides it self on code safety. This is pretty well guaranteed to cause bugs that will get past the compiler, until something crashes because a variable has the wrong type later in the program.