Sub topic 1
Declaring variables with let
This chapter covers the let statement, the construct Rust uses to bind a value to a name. Later chapters cover mutability, shadowing, and types in detail. Here the goal is to understand what a binding is, which forms let can take, and which errors you will meet first.
Prerequisites
This chapter assumes you can:
- Write and call simple functions and use loops in at least one programming language.
- Install Rust and run a program with
cargo runorrustc. - Read a basic compiler error message, including its error code and the line it points to.
You do not need to know ownership or borrowing yet. Where those ideas touch let, the chapter only mentions them.
What a binding is
A variable in Rust is called a binding. A binding connects a name to a value for some region of the program. The let keyword creates one.
fn main() {
let apples = 3;
let name = "Ferris";
println!("{name} has {apples} apples");
}The general form is:
let PATTERN: TYPE = EXPRESSION;Only let and the pattern are required. The type annotation and the initializer are optional, and the pattern is more flexible than a plain name, as later sections show.
Two points distinguish this from many languages:
letis a statement, not an expression. It has no value, so you cannot writelet a = let b = 1;.- A binding is scoped to the block
{ ... }that contains it. It exists from the line of theletto the end of that block.
fn main() {
let outer = 1;
{
let inner = 2;
println!("{outer} {inner}");
}
println!("{outer}");
// println!("{inner}"); // error[E0425]: cannot find value `inner` in this scope
}Bindings are immutable by default
By default, a binding cannot be reassigned after it receives its value. The next chapters explain the reasoning and the opt-in mut keyword. For now, this is the behavior you need to recognize:
fn main() {
let x = 5;
println!("x = {x}");
// x = 6; // error[E0384]: cannot assign twice to immutable variable
}If you uncomment the assignment, the compiler stops with E0384 and suggests adding mut. This is a compile-time check. There is no runtime cost and no way to bypass it by accident.
Declaring first, assigning later
A let does not have to initialize the variable. You can declare the name and assign it later, as long as the compiler can prove two things:
- The variable is assigned before every use.
- An immutable variable is assigned at most once on every path through the code.
fn main() {
let x = 5;
let mut count = 0;
count += 1;
let total;
total = x + count;
println!("total = {total}");
}Here total is immutable, yet the line total = x + count; is legal. It is the first and only assignment, so it counts as initialization, not reassignment.
This pattern is useful when the value depends on a branch:
fn main() {
let n = 7;
let label;
if n % 2 == 0 {
label = "even";
} else {
label = "odd";
}
println!("{n} is {label}");
}Each branch assigns label exactly once, so the compiler accepts it. Often an if expression is shorter, because if returns a value:
fn main() {
let n = 7;
let label = if n % 2 == 0 { "even" } else { "odd" };
println!("{n} is {label}");
}Prefer the expression form when it is readable. Use deferred assignment when the branches need several statements, or when you want the declaration to sit apart from the logic that fills it in.
Using a variable that may be unassigned
The compiler tracks assignment through control flow. If any path leaves the variable unset, reading it is an error.
fn main() {
let n = 7;
let label: &str;
if n > 10 {
label = "big";
}
// println!("{label}"); // error[E0381]: used binding `label` is possibly-uninitialized
}The fix is to add an else branch that also assigns, or to give label a value at declaration.
Patterns on the left-hand side
The left side of let is a pattern, not just a name. A pattern describes the shape of a value and can pull it apart. The simplest pattern is an identifier, which matches anything and binds it. Others work too:
fn main() {
let (x, y) = (3, 4);
let [a, b, c] = [10, 20, 30];
println!("{x} {y} {a} {b} {c}");
let (first, _) = (1, 2);
println!("{first}");
}Notes on this example:
let (x, y) = (3, 4);creates two bindings in one statement. This is destructuring. Later chapters cover tuples and arrays in full._is a pattern that matches a value and discards it without creating a binding.- The pattern must fit the value's shape.
let (x, y) = (1, 2, 3);fails with a mismatched types error, because the tuple has three elements.
A let pattern must be irrefutable, meaning it always matches. A pattern that can fail, such as Some(v) against an Option, is refutable and needs either match, if let, or let ... else.
fn main() {
let maybe: Option<i32> = Some(9);
// let Some(v) = maybe; // error[E0005]: refutable pattern in local binding
let Some(v) = maybe else {
println!("no value");
return;
};
println!("v = {v}");
}The else block of let ... else must diverge, which means it must leave the surrounding flow with return, break, continue, or a panic.
Unused variables and the underscore prefix
The compiler warns when a binding is never read:
warning: unused variable: `temp`Warnings do not stop the build, but treating them as noise hides real problems. If a binding is deliberately unused, start its name with an underscore:
fn main() {
let _scratch = 42;
let _ = "result ignored";
}The two forms differ. _scratch is a real binding that the compiler does not warn about. A bare _ is a pattern that does not bind at all. This difference matters later when a value has a destructor: let _ = value; does not move or keep the value alive, while let _guard = value; keeps it until the end of the scope. Keep this in mind, since guards such as lock handles rely on it.
Naming conventions
Rust enforces style through compiler lints. If you break the conventions, you get warnings, not errors.
| Item | Convention | Example |
|---|---|---|
| Local variables and functions | `snake_case` | `item_count` |
| Constants and statics | `SCREAMING_SNAKE_CASE` | `MAX_RETRIES` |
| Types and traits | `UpperCamelCase` | `UserAccount` |
If you need a name that collides with a keyword, you can write a raw identifier such as r#type. Renaming is usually clearer.
Type inference with let
You can state the type, but you often do not need to. The compiler infers it from the value and from how the variable is used later.
fn main() {
let a = 10;
let b: i64 = 10;
let c = 2.5;
let d: f32 = 2.5;
println!("{a} {b} {c} {d}");
}Without annotations, an integer literal defaults to i32 and a float literal defaults to f64. The compiler may choose a different type if later code demands it:
fn main() {
let n = 10;
let big: u64 = n;
println!("{big}");
}Here n is inferred as u64, not i32, because it is assigned to a u64. The full rules are the subject of a later chapter.
Inference sometimes cannot decide. The usual case is a call whose return type is generic:
fn main() {
// let parsed = "42".parse().unwrap(); // error[E0284]: type annotations needed
let parsed: u32 = "42".parse().unwrap();
let also = "42".parse::<u32>().unwrap();
println!("{parsed} {also}");
}Both fixes work. The annotation on the binding and the turbofish ::<u32> on the call give the compiler the missing information.
How a binding relates to ownership
A let binding does more than name a value. It also owns the value, and the value is dropped, meaning cleaned up, when the binding goes out of scope. You do not need the details yet, but one consequence shows up immediately with types that are not trivially copied:
fn main() {
let s1 = String::from("hi");
let s2 = s1;
// println!("{s1}"); // error[E0382]: borrow of moved value: `s1`
println!("{s2}");
}let s2 = s1; moves ownership from s1 to s2, and s1 can no longer be used. Simple types such as integers are copied instead, so let b = a; leaves both usable. A later part of the course explains the difference.
Common errors
| Error | Cause | Fix |
|---|---|---|
| E0384, cannot assign twice to immutable variable | Reassigning a binding declared without `mut` | Declare with `mut`, or create a new binding |
| E0381, possibly-uninitialized | Reading a variable that some path leaves unassigned | Assign on every path, or initialize at the `let` |
| E0425, cannot find value | Using a name outside the block where it was bound | Move the `let` to a wider scope |
| E0005, refutable pattern in local binding | A pattern that can fail used in plain `let` | Use `if let`, `match`, or `let ... else` |
| E0282 / E0284, type annotations needed | Inference has too little information | Add an annotation or a turbofish |
| E0382, use of moved value | Using a binding after its value moved elsewhere | Clone, borrow, or restructure |
Summary of key points
letbinds a name to a value in the enclosing block.- Bindings are immutable unless declared otherwise.
- A declaration can omit the value if every path assigns exactly once before use.
- The left side is a pattern, and plain
letaccepts only irrefutable patterns. - Types are inferred, and you add annotations when the compiler cannot decide.
- A name beginning with
_suppresses the unused warning, and a bare_binds nothing.
Exercise
The following code does not compile. Explain why, and give two different fixes. fn main() { let speed; let fast = true; if fast { speed = 100; } println!("{speed}"); }
Show answer
The if has no else, so when fast is false, speed is never assigned, and the compiler rejects the read with E0381 (possibly-uninitialized). Fix 1: add an else { speed = 50; } branch so every path assigns once. Fix 2: replace the declaration with an expression, let speed = if fast { 100 } else { 50 };.
Exercise
What is the difference between let _ = make_value(); and let _kept = make_value(); when make_value() returns a value that has a destructor?
Show answer
A bare _ is a pattern that does not bind, so the returned value is dropped immediately at the end of that statement. _kept is a real binding, so the value lives until the end of the enclosing scope and is dropped then. Use the named form when you need to keep something such as a lock guard alive.
Exercise
Why does let (a, b) = (1, 2, 3); fail, and why does let Some(v) = maybe; fail for an Option<i32>?
Show answer
The first fails because the pattern has two elements and the tuple has three, so the shapes do not match (mismatched types). The second fails because Some(v) is refutable: it does not match None, and plain let requires an irrefutable pattern (E0005). Use let Some(v) = maybe else { ... }; or if let instead.