Example: A variable and output in Rust
fn main() {
let x = 10;
println!("The value of x is: {}", x);
}
Output:
The value of x is: 10
Default variables are immutable, i.e. they cannot be changed. Rust does this to improve safety and concurrency.
Example: A mutable variable
fn main() {
let mut x = 10;
println!("The value of x is: {}", x);
x = 15;
println!("The value of x is: {}", x);
}
Output:
The value of x is: 10 The value of x is: 15
Immutable variables are like constants - that are values bound to a name and are not allowed to change. However, there are a few differences between constants and variables. You can't use mut with constants - constants are always immutable. Constrants are declared using the const keyword instead of let. THe type of the value for a constant must be annotated. Constants may also only be set to a constant expression and not the result of a function call or any other value that could only be computed at runtime.