Skip to main content

Variables

  • Define variables using let statement.
  • 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}");
}
  • let statement:

    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 let without needing to include any type explicitly, the compiler will infer the type.

variables2.rs

fn main() {
// Initialize the variable x to any integer
let x = 5;

if x == 10 {
println!("x is ten!");
} else {
println!("x is not ten!");
}
}
  • Variables need initialization.

  • But you don't need to initialize it on the same line, you can do something like this too:

    let x;
    x = 5;

variables3.rs

fn main() {
// Initialize the variable x to any integer
let x: i32 = 10;

println!("Number {x}");
}
  • Same as previous exercise, we just need to initialize the variable x.

variables4.rs

fn main() {
// Add mutable
let mut x = 3;
println!("Number {x}");

x = 5; // Don't change this line
println!("Number {x}");
}

variables5.rs

fn main() {
let number = "T-H-R-E-E"; // Don't change this line
println!("Spell a number: {}", number);

// Redeclare the number variable below
let number = 3;
println!("Number plus two is: {}", number + 2);
}

variables6.rs

// constant need type
const NUMBER: i32 = 3;

fn main() {
println!("Number: {NUMBER}");
}