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 are immutable

We declare variables using the let keyword, and despite calling them variables, in Rust they are immutable by default and the compile enforces this.

fn main() {
    let num = 2;
    println!("{num}");

    num = 3;
    println!("{num}");
}

This is the error message:

error[E0384]: cannot assign twice to immutable variable `num`
 --> src/main.rs:5:5
  |
2 |     let num = 2;
  |         ---
  |         |
  |         first assignment to `num`
  |         help: consider making this binding mutable: `mut num`
...
5 |     num = 3;
  |     ^^^^^^^ cannot assign twice to immutable variable

For more information about this error, try `rustc --explain E0384`.
error: could not compile `immutable-number` (bin "immutable-number") due to 1 previous error

  • let