An idea for adding functionality to Rust regarding shadowing

Instead, I suggest:
let x=3;
let x=4;
let mut x=5;

Do this:
let x=3;
hat x=4;
hat mut x=5;

Since Rust specializes in catching human oversights, and shadowing is somewhat akin to pointers, I believe that shadowing should also be caught at the syntactic level.

I'm tired today, I'm not sure this post is a joke or serious, but what does this syntax buy you?

Would you mind elaborating on this point? I don't see any semantic similarities between shadowing and pointers.


While I can see that sometimes a let i = 0; somewhere in a long function, deep within nested loops may cause subtle bugs, I don't think a syntax change for shadowing would be warranted, as these issues are usually best solved with better abstractions.

For instance, one could create a log of shading events—or a way to quickly jump to the start of each shaded period.

I could use shadowing in a parser. Or, in the context of prototyping—shadowing, mutability, and references—that makes for an excellent atomic unit. However, to facilitate this approach, the shading needs to be refined. I’m a creative newcomer. I’m reading a book on Rust, came across the concept of "shadowing," and decided to try explaining the idea.

Rust is not planning to make changes to its basic syntax.

Even if it's technically doable with an edition, it would create a lot of churn. There's still huge cost of teaching new syntax, convincing existing users to switch, updating books/tutorials and codebases.


As for the syntax itself, I'm not sure if it's a net positive. In many years of Rust programming I haven't found shadowing to be big a problem in practice. I rarely make such mistake and typically type mismatch or unused variable warning catches it anyway.

OTOH the proposed change reminds me of golang where var := can only be used once per binding, and it's been annoying me when refactoring code, because I can't temporarily comment out a block of code without having to update later uses.

What if, when an immutable variable is assigned a new value (which shouldn't be possible), it were to automatically shadow itself?

sha x;
x= 10;
x='c';
x=x;

There's a contingent in the community that quite strongly feels that the inability to overwrite variables which aren't declared mut is critical (e.g. that missing mut should never be downgraded to a lint you can disable), even in the face of shadowing.

If I understand your suggestion, it's close enough to "make all variables mut by default" that I'm sure it won't fly with that contingent.

That’s effectively how it works. In reality, the original immutable variable disappears, and a new one takes its place. Damn, it’s like something out of a horror movie—where a double steps out of a mirror to take a person’s place, and the person ends up inside the mirror.

Nope. I’m suggesting that we make it possible to track shading. Right now, there’s no simple way to find it.
let x="a";
let x="b";
let x="c";

and

let x="a";
hat x="b";
hat x="c";

Identical

Essentially, if something like this were added syntactically, the compiler could be made to track it with the same rigor as it does ownership cases. Alternatively, one could implement a mechanism for programmatically moving values across shadowing scopes.

When I learned Rust three years ago, my initial feeling was that

let a = 1;
let a = 2;

should be not allowed inside a scope, as a could be mut instead, and the code above could generate confusion, as a seems to be immutable (constant), but suddenly can change its value.

Shadowing with different types should be OK, as it is useful and should lead not to real surprises, like

let a = 1;
let a = my_int_to_str(a); \\ "1"

But sure, the Rust language is stable and will not change, and that is not really a serious issue.

If I understand you correctly, the human oversight in this case would be:

let a = 5;
let a = 10;

Your syntax suggestion with hat wouldn't change that because, nobody would use it. It's like if your'e want to convince your mechanic, that torx is the better screwdrive, if philips screws are in the part he wants to unscrew. You're solving the problem on the wrong side.

I simply don't see enough shadowing where there's confusion in real Rust code to make it worth the syntatic change. There's plenty of code I work with that contains shadowing, but in practice, it's confined to two cases:

  1. Inside an inner scope (e.g. a loop body) where the thing being shadowed from the outer scope isn't needed in the inner scope. It lets you have a clearer name in each scope without significant confusion.
  2. Within the same scope, when you're taking the same logical thing and changing its type - why should I need a different name for a CLI argument as an &OsStr and for it as f64 (the real type after parsing)?

For the first, this is things like:

let mut shadow = input.my_shadow();
// do things with shadow
let other_device_count = input
    .other_device_shadows()
    .into_iter()
    .filter(|shadow| shadow.is_valid())
    .count();
if other_device_count > MAX_DEVICES {
    shadow.set_overload();
} else if other_device_count == 0 {
    shadow.set_missing();
} else {
    shadow.set_normal();
}

Here, I've got a shadowing inside the closure - instead of shadow inside the closure representing the thing outside the closure parameters, it represents the thing inside the closure parameters. This shadowing is fine, because it makes semantic sense, and it's very clear what's going on.

For the second, it's things like

    let timeout = std::env::var("TIMEOUT_MS").or_else(|e| match e {
        std::env::VarError::NotPresent => Ok(String::from(DEFAULT_TIMEOUT_MS)),
        std::env::VarError::NotUnicode(_) => Err(Error::TimeoutMustBeNumeric),
    })?;
    let timeout: u64 = timeout.parse().map_err(|_| Error::InvalidTimeout)?;
    let timeout = Duration::from_millis(timeout);

where someone has decided that it's clearer to keep shadowing the previous name with a new type than it is to write this as:

let timeout = Duration::from_millis(
    std::env::var("TIMEOUT_MS")
        .or_else(|e| match e {
            std::env::VarError::NotPresent => Ok(String::from(DEFAULT_TIMEOUT_MS)),
            std::env::VarError::NotUnicode(_) => Err(Error::TimeoutMustBeNumeric),
        })?
        .parse::<u64>()
        .map_err(|_| Error::InvalidTimeout)?,
);

In this specific case, the second form is also readable, but it gets more complex when there's validation logic between reading the string and parsing it into the final form, and you're trying to not even attempt to parse into the final form if you can detect and clearly error on an incorrect format.

I can understand shadowing being a little confusing and possibly an avenue for errors, especially if you don't quite understand that you're not mutating the value you're working with but instead re-assigning the variable.

This code is a little strange to look at for example:

fn main() {
    let a = 1;
    let a = "Hello";
    println!("{}", a);
}

But at the same time, this is a common problem in almost every programming language I've used. Going too far off the conventional path means you're adding an extra thing to think about that most programmers already think about and understand. I'm not sure it's worth it.

It was worth a try. The reaction was interesting.

Yes. And this will create real problems and would fix nothing, because even in your syntax hat x="b" is not distinguishable from hat x="c". The end result: language that's strictly worse than what we have today. Go's story with := vs = is good indication.

Any proposal that looks, on the first glance, like a regression, needs really strong justification to explain what exactly it fixes.

I want it to be easier to find all the original, unshaded versions via search.

It's always worth discussing things - even if it's not a good idea in the end, it can be worth having the conversation that explains why.

I hope the examples at least helped explain why I don't think it's necessary - changing filter(|shadow| shadow.is_valid()) to filter(|hat shadow| shadow.is_valid()) just feels like noise for no readability gain. And in the end, that's what humans care about - reading the code and understanding it.

Sure, but… why? What would it help you with? You skipped the most important step: playing “five why?” game.

Sure, I understand what you want to achieve… but why? That's something that I, for one, have never wanted or needed… and I'm not alone. Which means you need explain why millions of people should suffer to help you do something that very few developers ever want or need.

Why is finding the original unshaded value more important than finding the previous shaded value (when there are two or more shaded values)?