TL ; DR:
-
In Rust, we use the snake_case convention to name our variables. It implies separating different words with an underscore (_), like this:
let company_name = "Apple"; let founding_year = 1976; let is_unicorn = true; let number_of_employees = 137000;
The compiler even prints a
non_snake_casewarning when a variable name is written in camelCase.
Full lesson:
Variable names must consist ONLY of letters, numbers and underscores and they must start with a letter or underscore.
Bad variable names:
let 18spam: i32;
let x.15: String;
let #name: bool;
If you try to create a variable with any of these names, Rust will throw an error.
Naming conventions: snake_case
Sometimes a variable name might consist of multiple words, for example if you want to store the first name of a person. You might be tempted to separate those names by whitespaces, like this:
let first name = "Kate";
This code will also throw an error.
When you name your variables in Rust, you use the snake_case convention:
snake_case = separate different words with an underscore (_), like this:
let first_name = "Jane";
let last_name = "Doe";
Other languages use camelCase (separate different words with capital letters), but in Rust this style is not the convention. It still compiles, and the compiler prints a non_snake_case warning:
let firstName = "Jane";
let lastName = "Doe";
It's important to be consistent. Do not combine both styles in the same code, like this:
let first_name = "Jane";
let lastName = "Doe";
Case sensitive:
Variable names are case sensitive:
let name = "Kate";
let Name = "Andy";
let NAME = "George";
println!("{} {} {}", name, Name, NAME); // Output: Kate Andy George
Although Rust compiles this (with non_snake_case warnings for Name and NAME), it's always confusing and a bad coding practice to differentiate variable names just by case!
Mnemonic Variable Names:
Since we programmers are given a choice in how we choose our variable names, there is a bit of "best practice".
Sometimes we want them short like x and y, but sometimes we want them descriptive, especially if they are important.
Here is a great example:
let a = 25;
let b = 13;
let c = a * b;
println!("{}", c);
compared to:
let hours = 25;
let rate = 13;
let pay = hours * rate;
println!("{}", pay);
Rust understands and is happy with both of these pieces of code. But it's clear which version makes your reader happier.
Assignment
Follow the Coding Tutorial and let's name some variables well!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
