November 2017
Intermediate to advanced
264 pages
5h 45m
English
Rust has to know the type of variables, because that way it can check (at compile time) that they are only used in ways their type permits. That way programs are type safe and a whole range of bugs are avoided.
This also means that we cannot change the type of a variable during its lifetime, because of static typing, for example, the variable score in the following snippet cannot change from an integer to a string:
// see Chapter 2/code/type_errors.rs
// warning: this code does not work!
fn main() {
let score: i32 = 100;
score = "YOU WON!"
}
With this, we get the compiler error, as follows:
error: mismatched types: expected i32, found reference
However, I am allowed to write this as:
let score = "YOU WON!"; ...
Read now
Unlock full access