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
languagethat holds"Rust".Print
I love Rust, using{}andlanguage.
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
liveschangeable by addingmut.Below the comment, set
livesto2, so the program printsLives: 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
pricewith a newlet pricethat 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 constantDAYS_IN_WEEKof typeu32with the value7.Inside
main, printA week has 7 daysusing 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
stepsthat starts at0.Add
2500tostepstwo times, on two separate lines.Print
Steps today: 5000usingsteps.
More in Rust Basics
Previous: Hello, World! · Next: Data Types