Start learning free

LESSON 11 OF 348 · VARIABLES

Variable Naming Rules in Rust in Rust

Lesson

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_case warning 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: camelCase and 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, you want to use one of these two conventions:

snake_case = separate different words with an underscore (_), like this:

let first_name = "Jane";
let last_name = "Doe";

camelCase = separate different words with capital letters, like this:

let firstName = "Jane";
let lastName = "Doe";

It's important to be consistent with the casing technique you use. Do not combine both of them 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 allows us to do this, 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 clearly 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.


STEP 1 OF 3
    Ctrl + Enter to check

    Variable Naming Rules in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free