[Rust] Variables
Rust's naming convention for variables is the same as other languages.
It can have the alphabet, number, and underscore, and can't start with numbers.
Immutable Variable
Variables are declared using the let keyword and by default it is immutable.
fn main() {
let x = 1;
x = 2; // error[E0384]: cannot assign twice to immutable variable
}
Mutable Variable
Using the mut keyword to make variables mutable.
fn main() {
let mut x = 1;
x = 2;
}
Constant
Constants are declared using the const keyword.
The naming convention for constants is to use all uppercase with underscores between words.
There are some differences between immutable variables and constants.
- mut keyword cannot be used
- constants are set only to a constant expression, not the result of a value that could only be computed at runtime
const HOURS_IN_SECONDS: u32 = 60 * 60;
Shadowing
If the declared variable is re-declared with the same name, the existing variable is shadowed.
fn main() {
let x = 1;
let x = x + 1;
{
let x = x + 1;
println!("x is {x}"); // 3
}
println!("x is {x}"); // 2
}
Once variables are declared it has data types, so other data types of values cannot be taken.
fn main() {
let mut x = "test";
x = x.len(); // error[E0308]: mismatched types
}
If we want to reuse variables with the same name for different types of values, shadowing may be useful.
fn main() {
let x = "test";
let x = x.len();
}