🎓 A1Learner
🔍

Rust Variables

A variable is a name that stands for a value. A Rust variable cannot change by default.

Create a variable

Use let to give a value a name:

let age = 30;
println!("age = {}", age);

Variables cannot change by default

Once set, a variable stays set. Trying to change it stops the compiler with error E0384:

let age = 30;
age = 31;

Say mut when a variable may change

Put the word mut after let, and the same change is allowed:

let mut count = 0;
count = count + 1;
println!("count = {}", count);

Rust guesses the type

You rarely write the type. Rust works it out from the value:

let price = 19.99;
let word = "hi";
println!("{} {}", price, word);

An unused variable warns you

A variable you never use brings a compiler warning. Start its name with _ to silence it:

let _draft = 5;

The rules for names

Names are case-sensitive: age and Age are two different variables. A name must start with a letter or an underscore. After that, it may use letters, digits and underscores. Nothing else. A name that starts with a digit, like 1age, does not compile.

let age = 30;
let _draft_age = 31;
let age2 = 32;
println!("{} {} {}", age, _draft_age, age2);

Example

fn main() {
    let mut count = 0;
    count += 1;
    count += 1;
    println!("count = {}", count);
}

Key points

  • A variable that is not allowed to change is called immutable
  • A let statement binds a value to a name.
  • Take a simple Copy type, like a number or a bool.
  • Then let copied = original binds a copy of original
  • Changing counts as assigning.
  • Writing count += 1 for an immutable variable fails.
  • It fails with error E0384, cannot assign twice to an immutable variable
  • Style for variable names is snake_case.
  • The words are lowercase, joined by underscores, like total_score.
  • The Comments lesson shows the same style for functions.
  • Constant names use SCREAMING_SNAKE_CASE instead
  • A helpful trick from the naming rules: start a name with _.
  • Do it when you must declare a value you do not use yet.
  • The compiler stays quiet about it.

In this example, count starts at 0. The word mut says count is allowed to change. The line count += 1 adds one, and it runs twice, so count becomes 2. The println! prints the value. If you removed mut, the compiler would stop you: you cannot change an immutable variable.

Note

In many languages, variables can always change.

In Rust, change is opt-in with the word mut.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What happens if you try to change a variable that was not declared with mut?