Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I was responsible for this design decision. For me, shadowing is really useful and I use it all the time. It's especially useful for creating new, slightly different modifications of earlier values when you don't want to keep coming up with new names all the time—this is common when making heavy use of immutable variables.

Some people don't like it, and if you don't you can use clippy to disallow it. From what I've seen, most Rust code does use shadowing.



> I was responsible for this design decision.

Dun dun duuun

I used to write a lot of C++ and my idea of immutability always was that if I see a variable declaration at the top of a function and scroll down to where it's used (without reading the code in the middle) I can assume nothing happened to the variable.

Then I started to learn Haskell something like a year ago and found out that shadowing is not only allowed but used by people. Especially in Haskell (or OCaml for that matter) where you can just use x' for a slightly modified version of x. I don't know. Maybe I get used to it one day.


Thank you, seriously. I use shadowing all the time, especially when unwrapping results and options.

I don't know if it's idiomatic, but I find it keeps things cleaner by not having to define lots of different names for essentially the same variable.


Are there any languages that use a different syntax for shadowing assignment? As in:

Scope 1

  let x = 1
  let x = 2
  => error, rebinding variable in scope not allowed
Scope 2

  let x = 1
  shadow x = 2
  => works!
Scope 3

  shadow x = 2
  => error: no variable x to shadow declared in scope

I wonder how well something like that would work in practice.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: