Variables
There are two types of variables in rust mutable and immutable. By default all variables are immutable in rust.
Variable declaration
1. Immutable
let num = 10;
let date: u8 = 15;
date = 28; // this will give error
// but redeclaring variable is fine
let date: u8 = 28;
2. Mutable
let mut date = 15;
date = 28;
Constant variables
Constant variable has to be in uppercase and type explicit.
1. const
const PI: u8 = 3.14;
const values are computed at compile time and therefore does not have a address as it is replaced by inline value during compilation, this means the compiler knows the value before the program runs. Because it is not tied to any particular memory address, you can have multiple constants with the same name in different scopes.
2. static
static PI: u8 = 3.14;
static variables have fixed address in memory for the entire duration of the program. This is useful for global state that needs to be accessed by multiple parts of your program.
static variables can be mutable.
static mut DATE: u8 = 15;
fn change_date() {
unsafe {
DATE += 1;
}
}
To update value of static variable, it has to be inside unsafe block.