Variables

Programming Languages · Rust Basics · 10 min

Store values with let, change them with mut, reuse names with shadowing and fix values with const.

Storing a value with let

A variable is a name for a value. Make one with let, then use the name wherever you need the value:

let pet = "cat";
println!("I have a {}", pet);
  • Create a variable language that holds "Rust".

  • Print I love Rust, using {} and language.

Changing a value with mut

In Rust, variables can't change by default. That keeps surprises away. If you want to change one, say so with mut (short for mutable, "changeable"):

let mut score = 0;
score = 10;

Try the task without mut first and read Rust's friendly error.

  • Make lives changeable by adding mut.

  • Below the comment, set lives to 2, so the program prints Lives: 2.

Shadowing

You can also write let again with the same name. This makes a brand new variable that hides the old one. It's called shadowing:

let x = 5;
let x = x + 1; // x is now 6

The new value can be worked out from the old one.

  • Below the comment, shadow price with a new let price that is the old price times 2.

Constants

A constant is a value that never changes, like the days in a week. Write it with const, a NAME IN CAPITALS and a type after a colon. Constants can live outside main:

const MAX_SPEED: u32 = 120;

u32 means "a whole number that is never negative". You'll meet more types in the next lesson.

  • Above main, create a constant DAYS_IN_WEEK of type u32 with the value 7.

  • Inside main, print A week has 7 days using the constant.

Put it together: a step counter

Let's count steps through the day. The count starts at zero and goes up, so it needs mut.

  • Create a changeable variable steps that starts at 0.

  • Add 2500 to steps two times, on two separate lines.

  • Print Steps today: 5000 using steps.

More in Rust Basics

Previous: Hello, World! · Next: Data Types