Sub topic 6
Bindings, shadowing, and moves in patterns
This chapter assumes you know Option and Result, match, and the basics of ownership and borrowing: moves, & references, and Copy types. It covers what happens to the names and values a pattern introduces. The same rules apply to if let, while let, let else, and let chains, so they are worth understanding once.
A pattern can introduce names
A pattern does two jobs at once. It tests whether a value has a certain shape, and it can bind parts of that value to new variables. In Some(port), the word port is not a lookup. It is a new variable that receives whatever sits inside the Some.
fn main() {
let config_port: Option<u16> = Some(8080);
if let Some(port) = config_port {
println!("listening on {port}");
}
}Where a binding is visible depends on the construct:
| Construct | Where the binding is visible |
|---|---|
| `if let PATTERN = expr { ... }` | Only inside the `if` block |
| `if let ... else { ... }` | Only inside the `if` block, not in the `else` block |
| `while let PATTERN = expr { ... }` | Only inside the loop body, fresh on each iteration |
| `let PATTERN = expr else { ... };` | In the rest of the enclosing block, after the statement |
The let else row is the odd one out. Its bindings leak into the surrounding scope on purpose, and a later chapter covers that construct in detail.
Shadowing inside patterns
A binding in a pattern can reuse the name of an existing variable. The new binding shadows the old one for the length of its scope. The old variable is not changed.
fn main() {
let value = 1;
let port: Option<u16> = Some(8080);
if let Some(value) = port {
println!("inner value: {value}");
}
println!("outer value: {value}");
}This prints inner value: 8080, then outer value: 1. Once the if let block ends, the inner value is gone and the outer one is visible again.
Shadowing is useful when the unwrapped value is the same thing as the wrapped one. Reusing the name saves you from inventing port_inner or maybe_port. The cost is that you can no longer reach the outer variable inside the block. If you need both, give one of them a different name.
The typo trap: a lowercase name is always a binding
A bare identifier in a pattern is a new binding, unless it names a constant, a unit struct, or an enum variant that is in scope. Suppose you meant to compare against a constant but wrote the name in lowercase, or misspelled it:
const LIMIT: u32 = 10;
fn main() {
let n = 10;
if let LIMIT = n {
println!("at the limit");
}
}This compares n with the constant LIMIT, so it is a refutable pattern. Now change LIMIT to a misspelled LIMT inside the pattern. The compiler no longer finds a constant by that name, so LIMT becomes a fresh binding that matches every value. The pattern is irrefutable, the if let always runs, and rustc emits an "irrefutable if let pattern" warning. Treat that warning as a sign that you wrote a binding where you meant a comparison.
Moves: a pattern takes what it binds
Binding follows the ordinary ownership rules. If the bound part of the value is not Copy, matching by value moves it out of the original.
fn main() {
let name: Option<String> = Some(String::from("Ada"));
if let Some(n) = name {
println!("got {n}");
}
// println!("{name:?}");
// error[E0382]: borrow of partially moved value: `name`
}The String inside name moved into n. After the if let, name is partially moved, and the compiler rejects any use of it as a whole. This happens even when the pattern did not match. The compiler tracks moves statically and cannot know which branch will run, so it takes the conservative reading.
You have three ways to avoid the move. Pick the one that fits.
- Match on a reference:
if let Some(n) = &name. Herenis a&String, andnamestays usable. - Convert first:
if let Some(n) = name.as_ref(). This does the same thing with an explicitOption<&String>. - Accept the move when you no longer need the original. This is the normal case for values you are consuming.
fn main() {
let name: Option<String> = Some(String::from("Ada"));
if let Some(n) = &name {
println!("got {n}, length {}", n.len());
}
println!("still have {name:?}");
}Default binding modes
You might wonder why Some(n) works against &name without you writing &Some(n). Rust applies default binding modes, often called match ergonomics. When a non-reference pattern like Some(n) meets a reference, the compiler automatically dereferences the value. It also switches the bindings to ref mode, so n becomes a reference to the inner part. A &mut scrutinee gives you &mut bindings.
fn main() {
let mut counter: Option<u32> = Some(0);
if let Some(c) = &mut counter {
*c += 1;
}
println!("{counter:?}");
}This prints Some(1). The variable c has type &mut u32, so you write through it with *c. The Option itself is modified in place.
Partial moves with struct patterns
Patterns on structs and enum variants with fields move only the fields they name. The fields you skip with .. stay in place, and Copy fields are copied.
enum Event {
Login { user: String, attempts: u32 },
Logout,
}
fn main() {
let event = Event::Login {
user: String::from("grace"),
attempts: 2,
};
if let Event::Login { attempts, .. } = event {
println!("attempts: {attempts}");
}
if let Event::Login { user, .. } = &event {
println!("user: {user}");
}
if let Event::Logout = event {
println!("logged out");
}
}The first if let binds only attempts, which is a u32 and therefore Copy. Nothing is moved, so event is still whole for the next two checks. If the first one had bound user by value, event would be partially moved and the later &event would not compile.
Binding and testing together with `@`
The name @ pattern form binds the whole matched value to name and also requires it to match pattern. This is the way to both test a range and keep the value.
fn main() {
let status: Option<u16> = Some(404);
if let Some(code @ 400..=499) = status {
println!("client error {code}");
}
}Without @ you would have to bind code first and check the range separately. Inside if let that check needs a nested if. That nesting is the problem let chains solve, in a later chapter.
Or-patterns must bind the same names
An or-pattern lets one pattern stand for several alternatives. When the alternatives bind variables, every alternative has to bind the same names, with the same types.
fn main() {
let result: Result<i32, i32> = Err(3);
if let Ok(v) | Err(v) = result {
println!("value either way: {v}");
}
}The names must match because the body runs after any alternative, so it needs to know that v exists no matter which one matched. Ok(v) | Err(w) is a compile error.
Bindings in `let else`
let else shows how bindings and shadowing work together. The binding lands in the enclosing scope, and shadowing the input name is the common idiom.
fn shout(input: Option<String>) -> String {
let Some(input) = input else {
return String::from("(nothing)");
};
input.to_uppercase()
}
fn main() {
println!("{}", shout(Some(String::from("hello"))));
println!("{}", shout(None));
}After the let else, input is a String, not an Option<String>. The parameter was moved into the pattern, and the new input shadows it. Since nothing later needs the Option, the move costs nothing. Inside the else block, the new binding does not exist yet, and you cannot use the moved value there either. If you need the original in the else block, match on a reference or clone before the statement.
Common errors
- "borrow of partially moved value". A by-value pattern moved a non-
Copyfield. Match on&valueor use.as_ref(). - "cannot move out of ... which is behind a shared reference". You matched through a reference but forced a by-value binding, for example with an explicit non-reference pattern on a
&value. Let default binding modes produce a reference. - Mismatched types in an or-pattern. The alternatives bind the same name with different types.
- Unexpected "irrefutable pattern" warning. An identifier you meant as a constant was parsed as a binding. Check spelling and case, or use a path such as
Self::LIMIT. - Expecting an
if letbinding after the block. It does not exist there. Uselet elseif the rest of the function depends on it.
Exercise
This code fails to compile with "borrow of partially moved value: title". What is the smallest change that fixes it, and what type does t have after the fix? let title: Option<String> = Some(String::from("Notes")); if let Some(t) = title { println!("{t}"); } println!("{title:?}");
Show answer
Change the scrutinee to &title, so the line reads if let Some(t) = &title. Matching through a reference makes default binding modes give t the type &String, so nothing is moved out and title can still be printed afterwards. Writing title.as_ref() also works and gives Option<&String>.
Exercise
Given let n: Option<i32> = Some(7); and let n_label = "seven";, write an if let that matches only values from 1 to 9 and binds the number to a variable named digit. Does the pattern touch n_label?
Show answer
Use if let Some(digit @ 1..=9) = n { println!("{digit}"); }. The @ binds the matched number and also checks the range. The pattern does not touch n_label. A pattern only introduces new names such as digit, and it shadows an existing variable only when it reuses that variable's name.