by KingOfCoders · 5y ago · 0 comments
a = "hello"
{
// new scope
a = 3
}
// a == "hello"
and is there a difference between Rust and Python?in Rust:
fn main() {
let a = 3;
let f = | | { a };
let a = "b";
println!("{}, {}", f(), a);
}
in Python: a = 3
def f ():
return a
a = "b"
print("{}, {}".format(f(), a))
The rust code outputs "3, b" while the python code outputs "b, b". The python code _assigns_ to the variable a, whereas the rust code creates a new scope and redefines a, shadowing it in the parent scope. a = 3
a = "x"
and both of these variables will exist at the same time with different times and potentially referable to from the outside. In python that cannot work, because there are no types. That's why in python the behavior is to always overwrite the existing variable, or create a new one in a local scope _if and only if_ this scope is somehow specified, i.e. by declaring a function.