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.

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

  • 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

variables5.rs

variables6.rs

Last updated