Variability of variables#
let#
In Rust, you declare variables using the let keyword as follows.
fn main() {
let apple = 10;
}However, since let is fundamentally immutable, trying to change the value of apple as shown below will result in an error.
fn main() {
let apple = 10;
apple = 20;
}error[E0384]: cannot assign twice to immutable variable `apple`let mut#
To modify a value, you need to use the let mut keyword as follows.
Here, mut stands for mutable.
fn main() {
let mut apple = 10;
apple = 20;
}Clearly distinguishing between mutable and immutable when using variables helps reduce human error, improves readability, enhances debugging efficiency, and ensures software quality.
Shadowing#
In Rust, the situation where the first variable apple is hidden by the second variable apple is called Shadowing.
When you use the variable apple, you refer to the second apple.
fn main() {
let apple = 1;
let apple = 2;
}In the following code, apple is shadowed within an inner scope (curly braces), and this is only valid inside the inner scope.
fn main() {
let apple = 1;
let apple = 2;
{
let apple = 3;
println!("@@@ apple: {apple}");
}
println!("### apple: {apple}");
}Here is the executed result.
In the inner scope, @@@ apple: 3 is printed, and after exiting the inner scope, ### apple: 2 is printed.
@@@ apple: 3
### apple: 2The type of a variable can be changed through Shadowing.
In the following code, the variable apple has been changed from an integer type to a string.
fn main() {
let apple = 1;
let apple = "semonan";
}constant#
In the following code, the let-based immutable variable apple and the const-based constant banana are similar in that their values cannot be changed, but there are clear differences between them.
fn main() {
let apple = 1;
const banana:u32 = 2;
}- A constant cannot be used with
mut. - A constant can never change its value while the program is running.
- When creating a constant, the Type of the value must be explicitly specified.