Rust Variable Names
Variable Names
In the Variables chapter, you gave your variables names like name and age.
A good name tells you what the value is for. When you read age, you know what the variable holds, without looking at its value.
Rust has a few rules for names. If you break them, the program does not compile. Rust also has a naming style that all Rust programmers follow.
Naming Rules
- Names can contain letters, digits and underscores (
_) - Names must begin with a letter or an underscore, not a digit
- Names cannot contain spaces or special characters like
!,-or# - Names are case-sensitive (
ageandAgeare two different variables) - Reserved words (Rust keywords, like
let,fnandif) cannot be used as names
Example
let age = 25;
let first_name = "John";
let player2 = "Liam";
println!("{}", age);
println!("{}", first_name);
println!("{}", player2);
Try it Yourself »
Names That Do Not Work
A name that starts with a digit gives an error, because Rust thinks it is a number:
Example
let 2nd_place = "Liam"; // Error
println!("{}", 2nd_place);
Try it Yourself »
To fix it, start the name with a letter instead, for example second_place.
The same goes for keywords. Rust uses words like let, fn, if, else, match, loop, while, for, mut and const for its own code, so they cannot be variable names.
Use snake_case
When a name has more than one word, Rust programmers write all letters in lowercase and put an underscore between the words. This style is called snake_case:
| Style | Example | Used in Rust for |
|---|---|---|
| snake_case | first_name, total_score | Variables and functions |
| UPPER_SNAKE_CASE | MAX_SPEED | Constants |
| UpperCamelCase | Person, Direction | Structs and enums (you will learn about them later) |
If you write a variable name in another style, like firstName, the program still runs. But when you build it on your own computer, the Rust compiler shows a warning: variable `firstName` should have a snake case name. It even suggests the name first_name.
Choose Clear Names
Short names like x are fine in small examples, but in a real program, use names that describe the value:
Example
let minutes_per_hour = 60;
let hours = 3;
let total_minutes = minutes_per_hour * hours;
println!("{} hours is {} minutes", hours, total_minutes);
Try it Yourself »
The same program with the names a, b and c would give the same result, but it would be much harder to understand what it does.