On 29/05/2013 6:48 AM, Gábor Horváth wrote:
Hi!
The following code snippet is well formed and prints 6:
fn main() {
let x = 5;
let x = 6;
println(fmt!("%?",x));
}
I was told this behavior is intentional. However I consider this pattern
as a potential source of errors.
It is intentional. It falls out automatically from supporting
shadowing-in-general (idents in enclosing scopes) and the ability to
declare new variables mid-block. Each new decl opens a new implicit
scope from its point-of-decl to the end of its lexical block.
Consider a larger function which one wants to modify. One declares a new
variable in the middle of the function, and if there was a name
collosion the whole meaning of the function is changed and the compiler
does not even provide us with a warning about it.
Yeah, a lint for this -- or for shadowing in general -- might be
worthwhile. Though some of us write this way ... somewhat regularly.
It's most common when you do something like:
let foo = complex_expression_returning_option();
let foo = foo.get_or_default(|| 10);
...
Where you're just repeatedly unwrapping and digging-in to a value,
changing type with each binding; making up throwaway names for the
intermediates that only last one line is tedious.
But even when you're not changing the type from one binding to the next,
it can be a nice way of doing a few "mutations" (rebindings) and then
leaving the value immutable through the rest of the block:
let foo = something();
let foo = something_else(foo) + bar;
// from here on in, foo is not mutated
// ...
"let" stands out in syntax-highlighting much more readily than a casual
assignment to a mutable variable.
It's a style issue.
-Graydon
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev