Lesson 2 - Variables

Variables allow programs to store information

For example:

let name = "Alex";
let age = 16;

Now we have two variables. The name variable stores “Alex,” and the age variable stores the value of 16.

Rust uses the let keyword to create variables.

We can then use println! to print the variable.

println!("{}", score);

The {} is a placeholder where Rust will insert the value.

One important difference in Rust is that variables cannot normally be changed after they are created.

let score = 10;
score = 20;

This will produce an error, since score is immutable by default.

If you want a variable to change, use the mut keyword.

let mut score = 10;
score = 20;
println!("{}", score);

Now, the program will correctly output 20.

Rust also allows shadowing, which is where you declare a new variable with the exact same name as a previously declared variable.

let x = 5;
let x = x + 1;
println!("{}", x);

The second x replaces, or “shadows” the first x. The final value of x is 6.