Use let
in rust to create a variable, which is constant by default. To declare a mutable variable, we need to add the key word mut
. Variable can only be declared in block scope.
let aNumber = 5; // num cannot be changed
let mut aChangableNumber = 3; // mutable
Note that the mut
keyword is also a type definition. Thus, if we want to pass a mutable variable to a function so that the function can change it, we need to do
inc_by_one(&mut aChangableNumber);
and the whole function would look like this
fn inc_by_one(x: &mut i32) {
*x = *x + 1
}
fn main() {
let mut x = 5;
inc_by_one(&mut x);
println!("x is {}", x);
}
Rust also has const
keyword to declare constants - value that are bound to a name and are not allowed to change.
const
can not be used with mut
(of course!), and the type of the value must be annotated. Constants can be declared in any scope, including the global scope.
This is a mechanism to allow you declare new variable with the same name as a previous variable, so the first variable is shadowed by the second. Thus, the second variable is what the compiler will see when you use the name of that variable. The second variable will take any uses of the variable name to itself until either itself is shadowed or the scope ends.
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}"); // 12
}
println!("The value of x is: {x}"); // 6
}
Benefits of this:
Every value in Rust is of a certain data type, and Rust is statically-strong-typed language.
let var_name : type_annotation = assignment
i8
, u8