Sub topic 6
Bindings, shadowing, and moves in patterns
This chapter assumes you know Option, match, and the basics of ownership and borrowing. It covers what happens to the names and values that a pattern introduces. These details cause most of the borrow-checker errors people hit with if let and let else.
Patterns create bindings
A name inside a pattern is a new variable, called a binding. In if let Some(port) = config_port, port exists only inside the if let block. In let Some(port) = value else { ... }, the binding lives in the surrounding scope, after the statement.
fn main() {
let config_port: Option<u16> = Some(8080);
if let Some(port) = config_port {
println!("inside: {port}");
}
// `port` is not in scope here.
}Shadowing is the usual style
A binding can reuse an existing name. The new variable shadows the old one for as long as it is in scope. Rust code often writes Some(x) = x because the unwrapped value is the one you want to use from then on.
fn first_word_len(text: Option<&str>) -> usize {
let Some(text) = text else {
return 0;
};
text.split_whitespace().next().map_or(0, str::len)
}
fn main() {
println!("{}", first_word_len(Some("hello world")));
println!("{}", first_word_len(None));
}After the let else, text is a &str, not an Option<&str>. The old name is shadowed, so you can't use the Option by accident.
With if let, the shadow ends when the block ends. Outside the block the original name still refers to the original variable.
Bindings move or copy by default
A pattern binds by value unless you say otherwise. If the matched part is Copy, such as u16, the binding gets a copy. If it isn't, such as String, the binding moves the value out of the original variable.
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
if let Some(name) = name {
println!("hello {name}");
}
// println!("{name:?}"); // error: use of partially moved value
}The String moved into the new name, so the original Option is partially moved. The compiler rejects any later use of it. Because the move happens only when the pattern matches, the compiler assumes the move may have occurred.
Match a reference to borrow instead
To keep the original, match on a reference. Rust then makes the bindings references too. This behavior is called default binding modes.
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
if let Some(n) = &name {
println!("hello {n}, length {}", n.len());
}
println!("still available: {name:?}");
}Here n has type &String, and name stays whole. Use &mut name when you need to change the contents through the binding.
| Scrutinee | Binding type for `Some(x)` | Original after match |
|---|---|---|
| `name` (owned `Option<String>`) | `String` | Partially moved |
| `&name` | `&String` | Still usable |
| `&mut name` | `&mut String` | Usable after the borrow ends |
| `config_port` (`Option<u16>`) | `u16` | Still usable, because `u16` is `Copy` |
Common errors
- Using the original after a move. The fix is to match on
&value, call.as_ref(), or clone before matching. - Expecting
if letbindings outside the block. Uselet elsewhen the name must live in the enclosing scope. - Shadowing by accident. If a binding in
Some(count)has the same name as a variable you meant to compare against, the pattern creates a new variable and doesn't compare. Patterns can't test equality with an existing variable. Add a guard or a&&condition instead.
Exercise
This code does not compile. Why, and what is the smallest change that fixes it? fn main() { let title: Option<String> = Some(String::from("Rust")); if let Some(t) = title { println!("{t}"); } println!("{title:?}"); }
Show answer
The pattern Some(t) binds by value, so the String moves out of title, which leaves title partially moved. The later println! then uses a moved value. Matching on a reference fixes it: if let Some(t) = &title. Now t is a &String and title stays intact.