Variables & Mutability¶
In Peel, safety is paramount. One way we achieve this is through strict control over mutability. Variables in Peel are immutable by default, which means once a value is bound to a variable name, you cannot change that value.
Declaration¶
Use the let keyword to declare a variable.
If you attempt to assign a new value to x, the compiler will throw an error:
Mutability¶
To declare a mutable variable, you must explicitly use the mut keyword. This signals your intent that the value will change, which is helpful for both the compiler and future readers of the code.
Shadowing¶
You can declare a new variable with the same name as a previous variable. This is known as shadowing. Shadowing is distinct from mutability because it creates a completely new variable, potentially even of a different type, while reusing the same name.
let spaces = " ";
let spaces = spaces.len(); // Shadows the previous string with an integer
println!("There are {} spaces.", spaces);
Shadowing Scope¶
Shadowing can be particularly useful within nested scopes.