Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 132 ยท Variables and Types

Variables and Mutability

Learn Rust variables - let, immutability by default, mut, shadowing versus mutation, type inference, late initialization, const, static and why unused variable warnings matter.

A variable is a name for a value. In most languages you create one and change it whenever you like. Rust makes the opposite choice: a variable is immutable by default, and you must write mut to allow changes. That one decision shapes a lot of Rust code. When you read a function and see let total = ... without mut, you know for certain that total never changes below that line, and the compiler guarantees it.

This lesson covers declaring variables with let, mutability, the related but different idea of shadowing, how types are inferred, declaring a variable now and giving it a value later, and the two kinds of global values: const and static. It also explains the compiler's unused-variable warnings, which beginners often find noisy until they learn what they are for. If you have not yet seen how Rust statements work, Rust Syntax is a short prerequisite.

Declaring a variable with let

A variable is introduced with the keyword let, a name, and a value:

Rust
let score = 10;

The name follows Rust's convention of snake_case: lowercase words joined by underscores. The value is computed, then bound to the name. Rust figures out that score is an i32 (a 32-bit signed integer, the default for whole-number literals) without being told; you will see more about that shortly.

Now try to change it:

Rust Assigning twice to an immutable variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler refuses with error[E0384]: cannot assign twice to immutable variable score``. It points to the first assignment, to the second, and suggests: consider making this binding mutable. It also adds a warning that the first value is never read, which makes sense, since the program never uses 10.

The fix is to say mut at the declaration:

Rust mut allows reassignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The word mut is a promise to the reader: "this value will change." Because it is explicit, you can scan a function for mut to find everything that varies, and everything else is a fixed fact. Beginners sometimes add mut to everything. The compiler pushes back: if a variable is declared mut but never modified, you get the warning variable does not need to be mutable. Treat that warning as a request to remove the keyword.

Mutability belongs to the binding, not to the type. let mut v = Vec::new(); lets you push into the vector. let v = Vec::new(); does not, even though the type is identical. This is different from languages where an object is inherently changeable or not.

Why immutable by default?

There are three practical reasons.

  1. Reasoning. If a value cannot change, you do not have to track what other code might do to it. A function with only immutable locals is easy to read from top to bottom.
  2. Safety with sharing. Rust's most important rule, covered in Borrowing, is that you may have many readers or one writer of a value, never both at once. Immutable bindings are the easy, common case that needs no ceremony.
  3. Optimization. The compiler knows a non-mut value does not change, so it can keep it in a register or evaluate it at compile time.

A good habit is to start every variable without mut, and add it only when the compiler complains and you agree that the value really must change.

Shadowing: a new variable with the same name

Rust lets you declare a new variable with the same name as an earlier one. The new one shadows the old one: from that point on, the name refers to the new variable.

Rust Shadowing with let

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first block turns text into a number in three steps, reusing one name instead of inventing input_trimmed, input_number and input_doubled. Each let creates a brand-new variable (note that the type changes from &str to i32). The old variable still exists in memory until its scope ends, but you can no longer name it. The code prints 84.

In the second block, let x = x * 10; inside braces shadows x only until the closing brace. After the block, x is 5 again. The output is inner x = 50 then outer x = 5.

Shadowing versus mutation

Shadowing looks similar to mut but is different in two important ways:

let mut x then x = ... let x = ... again
Creates a new variable No, changes the same one Yes
Can change the type No Yes
Variable afterwards Still mutable Immutable (unless you write mut again)

The type difference is the practical one. This does not compile:

Rust mut cannot change the type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You get error[E0308]: mismatched types, with expected &str, found usize``. A variable has one type for its whole life. If you really want to transform a value into a different type, shadow it: let spaces = spaces.len();.

Use shadowing for transformations (clean text, parse it, then use the number) and mut for values that genuinely accumulate or update (a counter in a loop). A common misuse is shadowing inside a loop body hoping to change an outer variable; it will not, because the shadow disappears at the end of the iteration.

Type inference

You rarely write types for local variables, because the compiler infers them from how the value is created and used:

Rust Inferred types and their sizes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The sizes are 4, 8 and 2 bytes: i32, f64 and u16. Several things happened there.

  • Plain integer literals default to i32 and plain decimal literals to f64.
  • You can pin the type with an annotation after the name (let e: u8 = 200;) or with a suffix on the literal (3_u64; the underscore is optional and only for readability).
  • Vec::new() alone has no element type. The compiler waits, sees v.push(1u16), and concludes that v is a Vec<u16>. Inference works across the whole function, not only on one line.

When inference cannot decide, it asks you. For example, "5".parse().unwrap() has too many possible targets and fails with error[E0284]: type annotations needed. Add let n: i32 = ... or parse::<i32>(). The topic continues in Type Aliases, the Never Type and Inference, and the numeric types in Integers, Floats, bool and char.

Add annotations deliberately when they help a human reader (a function that returns a computed number, a public constant) and skip them when the type is obvious.

Declaring first, assigning later

A let does not need a value at once. You may declare a variable and initialize it afterwards, as long as the compiler can prove it is initialized before every use, and (for a non-mut variable) assigned exactly once:

Rust Late initialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both branches assign label once, so label is fine without mut. This is occasionally useful when each branch needs several statements; often an if expression is shorter (let label = if n % 2 == 0 { "even" } else { "odd" };), which is how you will usually write it. See if, else if and else.

If one path forgets to assign, the compiler notices:

Rust Possibly uninitialized variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is error[E0381]: used binding total is possibly-uninitialized, and the diagnostic even points at the if and says that an else arm might be missing. Rust has no "default zero" for locals and no way to read garbage memory by accident; that class of bug is simply not expressible. The annotation total: i32 is optional here, because inference could learn the type from the later assignment; it simply makes the intent clear.

Scope and destructuring

A variable lives from its let to the end of the block { ... } that contains it. When the scope ends, the value is dropped, which means its memory and any resources it owns are released. You will see exactly how this works in Ownership.

let also accepts patterns, not just names. You can pull a tuple apart in one statement, and ignore parts with _:

Rust
let (width, height) = (1920, 1080);
let (first, _) = (10, 20);

Patterns are a big subject of their own: Patterns.

Unused variables and the underscore

The compiler warns about variables you create and never read: warning: unused variable: `unused` with the help text if this is intentional, prefix it with an underscore: _unused``. These warnings catch real bugs, such as misspelling a variable name so that the intended one stays unused. When you do mean to ignore a value, start the name with an underscore, or use a bare _ which does not bind at all:

Rust Underscore names silence unused warnings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

There is a subtle difference. _ignored still creates a variable that lives until the end of its scope, while _ never binds, so a value matched against it can be dropped immediately. This matters later with guards and locks (let _guard = lock(); keeps the lock, let _ = lock(); releases it at once, a classic mistake).

Constants

A constant is a value known at compile time. You declare it with const, a SCREAMING_SNAKE_CASE name, and a mandatory type. It can live in any scope, including outside every function, and it cannot be mut.

Rust const values and const fn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output is 4 players, 86400 seconds per day and area = 144, buffer length = 9. Notice that 24 * 60 * 60 is written as an expression, so the value stays understandable. The compiler computes it. A const fn is a function that may be called in constant context, so even array lengths can come from it.

Think of a const as a name that is pasted wherever it is used. Every use is effectively a fresh copy of the value, which is why a constant has no single address. Constants are the right choice for numbers, limits, string tables and configuration that never change. Compare with let: a let is computed at run time and may depend on input; a const may not.

You cannot assign to one, either. LIMIT = 6; for a const LIMIT gives error[E0070]: invalid left-hand side of assignment.

Statics

A static is a value with a fixed place in memory for the entire run of the program. There is exactly one of it, so references to it are all the same address, and it can hold things that need an identity, such as an atomic counter or a lookup table you want to share without copying.

Rust A static atomic counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program prints hello, hits = 2. A static is immutable like everything else, but the atomic type has interior mutability: it can be changed through a shared reference, safely, even from several threads. Atomics and Refcell and Cell explain the mechanism.

There is also static mut, a global that anyone can change. Using it is unsafe, because two threads could modify it at the same time (a data race), and the 2024 edition also denies taking references to it. The compiler is blunt about it:

Rust Using a mutable static (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each use fails with error[E0133]: use of mutable static is unsafe and requires unsafe block. Wrapping both in unsafe { ... } silences the compiler but not the danger. Prefer an atomic, a Mutex inside a static (Mutex::new is a const fn), or a LazyLock for lazily built data. Unsafe Rust is the place to study the exceptions.

const or static?

const static
Memory Inlined at each use, no fixed address One location for the whole program
Mutable Never Only static mut (unsafe)
Typical use Numbers, sizes, small tables Shared state with identity, big read-only tables, atomics
Initializer Constant expression Constant expression

When in doubt for a plain value, use const. Reach for static when you need one shared object, or when a big table should not be copied into every place it is used.

Common mistakes

  • Adding mut to everything. Start immutable and let the warnings guide you.
  • Expecting shadowing to modify an outer variable from inside a block or loop. It creates a new variable that disappears with the scope.
  • Forgetting the type on const and static. It is required.
  • Using static mut for a counter. Use an atomic.
  • Ignoring unused-variable warnings. They often reveal typos and logic errors.
  • Writing let _ = lock(); when you meant to hold the lock: the _ pattern drops the guard at once.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you assign to a variable declared with let x = 1;?

    Variables are immutable by default, and the borrow checker enforces this at compile time. Write let mut x = 1; to allow assignment.
  2. 2. Which of these can shadowing do that mut cannot?

    A shadowing let creates a new variable, so it may have a different type. A mutable variable keeps its single type for its whole life.
  3. 3. Why does let x: i32; if cond { x = 1; } println!("{x}"); fail to compile?

    Rust requires every use of a variable to be preceded by an assignment on every possible path. The error is E0381: used binding is possibly-uninitialized.
  4. 4. What does the leading underscore in let _count = 3; do?

    A name starting with an underscore silences the unused variable warning. It is still a normal variable that lives until the end of the scope; only the bare _ pattern does not bind.
  5. 5. Which statement about const is true?

    A const must have an explicit type and a value the compiler can compute. It can never be mutable, is inlined at each use, and may be declared at module level.

Summary

  • let binds a name to a value; bindings are immutable unless declared with let mut.
  • mut is a visible promise that a value changes; unneeded mut produces a warning.
  • Shadowing (let x = ... again) creates a new variable and may change the type; assignment to a mut variable cannot.
  • Types are inferred from literals and use (integers default to i32, decimals to f64); annotate with : Type or a suffix such as 3_u64 when needed.
  • A variable may be declared first and assigned later, but the compiler must see an assignment on every path before any use.
  • Prefix intentionally unused names with _; the warning exists to catch typos.
  • const is a type-annotated compile-time value inlined at each use; static is one shared memory location; avoid static mut and prefer atomics, Mutex or LazyLock.

Next: Integers, Floats, bool and char looks at the basic value types in detail.