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

Cannot change the type of a variable

So far when declared variables we have not declared the types of the variables, but behind the scenes Rust maintaines a type-system and enforces it. When we first assign a value to a variable - usually when we declare the variable - Rust will infere the type of the variable from the value we assigned to it.

Then when we try to change the value Rust will make sure we can only change it to a value of the same type.

In this example when we declared the variable answer we assigned a (literal) string to it.

If late we try to assign a number, Rust will stop us with a compilation error.

fn main() {
    let mut answer = "What is the answer";
    println!("{answer}");

    answer = 42;
    println!("{answer}");
}

The compilation error:

error: expected `;`, found `answer`
 --> src/main.rs:3:25
  |
3 |     println!("{answer}")
  |                         ^ help: add `;` here
4 |
5 |     answer = 42;
  |     ------ unexpected token

error[E0308]: mismatched types
 --> src/main.rs:5:14
  |
2 |     let mut answer = "What is the answer";
  |                      -------------------- expected due to this value
...
5 |     answer = 42;
  |              ^^ expected `&str`, found integer

For more information about this error, try `rustc --explain E0308`.
error: could not compile `cannot-change-type` (bin "cannot-change-type") due to 2 previous errors