Variables
Define variables using
letstatement.Variables need initialization. By default variables are immutable unless explicitly declared using
mut.We can declare a new variable with the same name as a previous variable, this is called shadowing.
Constants are values that are bound to a name and are not allowed to change.
Constants are always immutable.
The type of the value MUST be annotated.
Reference: Variables and Mutability
variables1.rs
fn main() {
// Adding let
let x = 5;
println!("x has the value {x}");
}letstatement:A let statement introduces a new set of variables, given by a pattern. The pattern is followed optionally by a type annotation and then either ends, or is followed by an initializer expression plus an optional else block.
Reference: https://doc.rust-lang.org/reference/statements.html#let-statements.
In this exercise we only need to add
letwithout needing to include any type explicitly, the compiler will infer the type.
variables2.rs
Variables need initialization.
But you don't need to initialize it on the same line, you can do something like this too:
variables3.rs
Same as previous exercise, we just need to initialize the variable
x.
variables4.rs
By default variables are immutable, so we need to explicitly declare mutability by adding
mut.
variables5.rs
We can declare a new variable with the same name as a previous variable
In Rust this is called shadowing.
You can read more about this topic here: https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing.
variables6.rs
Constants are values that are bound to a name and are not allowed to change.
Constants are always immutable.
The type of the value MUST be annotated, so adding
i32will fix the code.
Last updated