Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Variables

Type annotation

  • type is either inferred from the context or explicitly specified by the developer
// inferred type
let x = 42;
let y: u32 = x;

// explicit type 
// let <variable_name>: <type> = <expression>;
let y: u32 = 48;

Initialization

  • a varible does need to be initialized until it is used
let x: u32;

Function’s parameters

  • function’s parameters are variables too
  • type annotation of parameters is mandatory
fn add_one(x: u32) -> u32 {
    x + 1
}

Mutability

  • by default the variables are immutable unless you make it mutable with mut
fn main () {
    let x = 5;
    let mut y = 6;
    println! {"Variable x equals to {x} and cannot be changed."};
    println! {"Variable y equals to {y} and can be changed."};
    y = 8;
    println!("New value of variable y equals to {y}.")
}

Constants

  • The type of the value must be annotated.
  • Can be declared in any scope, including the global scope.
  • It may be set only to a constant expression, not the result of a value that could only be computed at runtime.
  • The naming convention: all uppercase with underscores between words.
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

Shadowing

  • A variable can be shadowed by using the same variable’s name and use it with let.
  • The second variable overshadows the first variable until either it itself is shadowed or the scope ends.
fn main() {
    let x = 5;
    println!("The value of x is {x}.");

    let x = x + 2;
    println!("The new value of x is {x} and overshadows the previous value.");

    {
        let x = x * 2;
        println!("The value of x in inner scope is {x}.");
    }

    println!("The value of x outside the inner scope is again {x}");

}
  • Shadowing differs from marking a variable as mut:
    • as the value cannot be changed without using the let
    • the variable is still immutable after transformation with let
  • Shadowing can also change the type of the value
fn main() {
    let spaces = "   ";
    println!(" Variable spaces is a string.");
    let spaces = spaces.len();
    println!("The type of variable spaces is now a number and spaces equals to {spaces}.");
}