There's absolutely a language where you don't need let
, python does this, for example. Rust just isn't that language. Let's assume we're talking about a new language with Rust's features, rather than adding this now, just to avoid the also valid compatibility issues.
Firstly, foo = bar;
already has a meaning: assign bar
to the existing foo
. Easy enough to fix: only have it declare a new variable if there isn't one already, right?
Except now declaring a variable somewhere else can now change the meaning of this code without any visible difference. That's bad for being able to understand what some code does. Worse, what if you meant to assign to some variable, but it got renamed, so you're just declaring and then discarding a variable.
You can fix these problems too: use a python style nonlocal foo;
to pull in an external foo
, or use separate declare and assign ops, say =
and :=
. But that doesn't seem to be much of an improvement over let
anymore. And there's more!
How do you declare mutable variables? mut foo = bar;
? What about declaring without assignment? Just foo;
? That seems a bit ugly and confusing.
Why should let get this magic, but not fn
, mod
or any of the other declaration keywords? You could also infer those:
{ args } = std::env;
main() {
debug = args().includes("--debug");
if debug {
debug::enable();
}
// ...
}
debug {
Data { value: String }
enable() {
Data { value: "some string" }
...
}
}
Etc., and you could make that work, but you quickly start to see how samey everything looks, and you often have to start encoding guidelines like "types start with a capital, everything else lowercase" as part of the syntax. Is that actually a better language? Certainly there are people who would like that, but it's clear it's a different language to Rust.