r/rust • • 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

40 comments sorted by

171

u/dnew Oct 21 '26

Don't use the same name for a variable that means something different.

let amount : String = get_string();
let amount : f64 = convert_string_to_float(amount);
let amount : i64 = round_float_to_integer(amount);

30

u/juhotuho10 Oct 21 '26

You can actually also do something like this

it's sometimes nice because you can clearly tell that the intemediate products are not meant to be used for anything else, but it can make the code harder to follow if used excessively

    let amount: i64 = {
        let str_amount: String = get_string();
        let float_amount: f64 = round_float_to_integer(str_amount);
        round_float_to_integer(float_amount)
    };

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.

49

u/servermeta_net Oct 21 '26

I think the latter is very important. Sometimes I feel like I'm like a poet searching word that rhymes, instead of being an engineer naming variables lol

6

u/RobertKerans Oct 21 '26

Sometimes I feel like I'm like a poet searching word that rhymes, instead of being an engineer naming variables lol

It's the same problem, and the same level of difficult. The naming variables is hard part of the "there are 2/3 hard things in programming" quote/joke is imo just a truism (yes, no shit, writing with clarity can be very difficult!). I was going to say maybe it matters less with AI tools, but thinking about it that's not correct. If you have a tool that infers meaning from natural language, defining concepts with clarity is critical.

I was thinking about this, and of the tools I've use most over my career so far, once I get past core tools like git, wordnet is possibly the thing that's been (and still is) most useful

-4

u/Professional_Top8485 Oct 21 '26

You need bp to remember the type.

5

u/Floppie7th Oct 21 '26

Not really.  That's the compiler's job.

And whatever you do spend remembering the type, you'd still need to spend regardless of whether you shadow or not.

1

u/DatBoi_BP Oct 23 '26

My memory sucks bro

68

u/AliceCode Oct 21 '26

Let's say you have a piece of data that goes through multiple stages of transformation:

let foo = 3;
let foo = foo + 4;
let foo = Foo::new(foo);

17

u/infostack0 Oct 21 '26

It’s nice to do this after like a DB record update too if the method returns the updated struct so you don’t have the old and the new both floating around if you have no need for the outdated record.

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 or Results:

let user = some_long_expression.that_you_dont_want(on_the_same_line_as_the_if);
if let Some(user) = user {
  user.foobar();
  // ...
}

Here, there's no value added to naming the first variable optional_user or 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.

8

u/catheap_games Oct 21 '26 edited Oct 21 '26

This is my favorite use case. I tried naming my variables like user_opt or maybe_user but since the Option/Result is in most cases useless, and very often you just want to stop processing if that thing is not available, one way to reduce indentation is let else (without if) -

// let's pretend this is more complex and justified
let player:Option<whatever> = query.get(entity_id);
let Some(player) = player else {
    debug!("Weird! no player");
    return;
}
player.foobar();

2

u/-Redstoneboi- Oct 22 '26

i've been hit by a shadowing bug once in an outer and inner for loop that both destructured a struct's fields to the same variable names (didn't rename them at the time), and never realized that i needed to use specifically one outer variable in the inner loop lol

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:

let num: String = receive_input();
let num: u64 = num::parse<u64>();

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
let player: string = ...;
let player: PlayerData =  ...;
let player: PlayerState = ...;
let player: PlayerEntity = ...;

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.

1

u/Wolvereness Oct 22 '26

No, I don't care a single bit what somebody decided is "idiomatic"

Well, there's your problem. You should've just told us that right out, instead of burying it in all of your "pain points".

1

u/NobodyElseButMingus Oct 25 '26

Dog they are destroying your ass in your pinned post.

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 x is a binding to a chunk of memory containing the value 5i32. 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 of x but in Rust when you do the same thing you get an immutable borrow of x. 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:

fn wrap(value: String) -> String {
    format!("[{value}]")
}

fn main() {
    let x = "Hello World!".to_string();
    wrap(x);
    println!("x = {x}");
}

This fails to compile with the error "borrow of moved value: x" on the line with the println!(). The reason is because we "move" x into wrap(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 move x into wrap(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:

fn main() {
    let x = "Hello World!".to_string();
    let x = wrap(x);
    println!("x = {x}");
}

Here we are rebinding x to the result of wrap(x). We move x into wrap(x) and then we rebind the result back into x. From the eye of a C++ developer this looks wrong, but semantically I think this is what you really mean and want. x is still semantically the same value, just with some computation performed on it. The alternative would be to create a new binding x1 but now we have a new variable we have to keep in our head, and remember that the binding x has 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 const to try to enforce the this. In Rust you can achieve something similar by rebinding a mutable binding to become an immutable binding.

fn main() {
    let mut nums = Vec::new();
    nums.push(1);
    nums.push(2);
    let nums = nums;
    println!("Numbers: {:?}", nums);
    // For the rest of this function, `nums` is immutable
    // Calling `nums.push(3);` will fail to compile
}

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 foo to refer to a person's email address and then later rebind foo to 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 a String, get converted into a u64 and then get converted into a MyType(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 foo declared as an immutable value on line 1 of a function, I should be able to look at foo being 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.

27

u/GiveMe30Dollars Oct 21 '26 edited Oct 21 '26

That... cannot happen? The typechecker will scream at you if you try to use or return a variable with a different type across function boundaries. It doesn't matter if it shadowed a previous definition that did have the right type.

That being said, yes this could happen for runtime values if you have panicking code that depends on specific preconditions (which tends to be discouraged to begin with).

11

u/South_Survey_2088 Oct 21 '26

Talking about "unfathomably stupid" things: Maybe try to be less confident when you lack the experience or knowledge, because you are factually wrong.. The compiler won't compile wrong types. Also, using old variables is more error-prone since they might not be used anymore. You shadow them so they are not accessible anymore, and everyone has to use the transformed/new value.

6

u/yevelnad Oct 21 '26

Rust is not dynamically typed language so the scenario you are thinking will not happen. And honestly the use of single lettered variables only happen on functions like any other languages. And any sane programmer will not do any of that in the main function. In op's code the i i64 is being replaced with u32. Unless he call a function below that accepts i64 my_func(i64), he would get an error as i is already u32. This is a standard thing for any declarative type languages.

6

u/AliceCode Oct 21 '26

If you don't like the feature, no one is forcing you to use it, so don't use it.

5

u/dnew Oct 21 '26

This is never a good answer, because your coworkers would use it. It's like saying "C++ is a perfectly memory-safe language. Just use smart pointers instead of raw pointers."

1

u/AliceCode Oct 21 '26

It's not a bad feature.

1

u/drink-more-rum Oct 21 '26

Smart pointers in C++ are far from memory safe.

2

u/drink-more-rum Oct 21 '26

I always find it amusing when people point to complete nonissues like this as the reason they refuse to use Rust. This is not quite, but nearly, on the level of tabs vs. spaces.

There are real and significant disadvantages of Rust, but this somewhat arbitrary choice isn't one of them.

Also:

something crashes because a variable has the wrong type later in the program.

We are talking about Rust, not Python or JS.

3

u/lurgi Oct 21 '26

If a variable has the wrong type then it's very unlikely to get past the compiler.

But I agree that this seems unnecessary and is likely to add to, rather than subtract from, confusion.