Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Rust allows declaring same variable name twice in a scope? [duplicate]

Tags:

rust

First time I am encountering a typed language allowing to declare a variable name twice in the same scope. Wouldn't there be a chance to override an existing variable by mistake? What advantage does it bring?

like image 973
naras Avatar asked Sep 02 '25 10:09

naras


1 Answers

There is a chapter in the book about this.

Shadowing is different from marking a variable as mut, because we’ll get a compile-time error if we accidentally try to reassign to this variable without using the let keyword. By using let, we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed.

The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name. For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, but we really want to store that input as a number

let spaces = "   "; // String
let spaces = spaces.len(); // number

In short, it allows you to "modify" a value, in a way that is technically immutable. Rust ensures that you cannot use the shadowed variable, so it's perfectly typesafe.

I'm no Rust expert, but from a language design perspective it's an interesting thing to encourage. But I think the point is to discourage the use of mutable values whenever possible by allowing you to immutably override a name with a new type and value.

like image 78
Alex Wayne Avatar answered Sep 04 '25 09:09

Alex Wayne