Like other programing languages, to hold data we need some things called constant and variable.
CONSTANT
We could not change value of a constant. Good choice to store value that is not changed over time.
const SECONDS_OF_ONE_MINUTE: i32 = 60;
const SECONDS_OF_ONE_HOUR: i32 = SECONDS_OF_ONE_MINUTE * 60;
const SECONDS_OF_ONE_DAY: i32 = SECONDS_OF_ONE_HOUR * 24;
VARIABLE
1) Immutable variable (default and favor by Rust):
After assigning a value to a variable by keyword let, we could not re-assign it. For example:
let var = 1;
println!("value: {var}");
var = 2; // Will cause error at compile time.
println!("value: {var}");
At this point, it is quite similar to constant, right?
But there are 2 things different between immutable variable and constant:
- We can use variable shadowing to change variable value. Just repeat the
let
keyword. But there is a small thing behind the scene. Rust creates another new variable with a new memory slot and with a same name. Not the original one. IMO, its functionality seems to run contrary to its name (immutable but changeable by somehow)
let var = 1;
println!("value: {var}");
let var = 2; // Is OK
println!("value: {var}");
- Mutable was born to serve this purpose.
2) Mutable variable:
Just put mut
keyword after let
:
let mut name = "Unknown";
name = "Danh";
Easy huh?
Reference: https://doc.rust-lang.org/stable/book/ch03-01-variables-and-mutability.html
Top comments (0)