Sub topic 12
Moves, References, and Binding Modes in Patterns
A pattern can test a value and also bind parts of it to new names. Each binding either moves, copies, or borrows the matched part. This chapter explains which of the three happens and why. It also covers the ownership errors that come with each.
This chapter assumes you know Rust's ownership rules (moves, shared and mutable references), the Copy trait, and how match and if let destructure enum variants and structs.
A binding takes ownership by default
Binding a name inside a pattern works like an assignment. If the matched part is Copy, the binding copies it. If not, the binding moves it out of the original value.
enum Message {
Text(String),
Quit,
}
fn main() {
let msg = Message::Text(String::from("hello"));
match &msg {
Message::Text(s) => println!("borrowed: {s}"),
Message::Quit => println!("quit"),
}
if let Message::Text(s) = msg {
println!("moved: {}", s.len());
}
}The match is on &msg, so s is a &String and msg stays intact. The if let matches msg by value, so s is a String moved out of the enum. After that line, msg can no longer be used as a whole.
Partial moves
A move only takes the parts that a pattern actually binds. The rest of the value stays usable.
struct User {
name: String,
email: String,
age: u32,
}
fn main() {
let user = User {
name: "Ada".to_string(),
email: "[email protected]".to_string(),
age: 36,
};
let User { name, age, .. } = user;
println!("{name} is {age}");
println!("{}", user.email);
}Here name is moved, age is copied, and .. ignores email. Using user.email is fine. Using user.name or passing user whole to a function would be a compile error, because part of user has moved. Partial moves are only allowed when the type does not implement Drop.
Two names look alike but behave differently:
_is not a binding. It never moves anything, solet (first, _) = pair;moves onlypair.0._otheris a real binding with a leading underscore. It moves the value, and only suppresses the unused-variable warning.
fn main() {
let pair = (String::from("a"), String::from("b"));
let (first, _) = pair;
println!("{first} {}", pair.1);
}Default binding modes
Matching a reference against a non-reference pattern would be tedious if you had to write the reference syntax everywhere. Rust handles this automatically. When the value being matched is a reference and the pattern is not, the compiler dereferences the value and changes the default binding mode:
- Matching a
&Tswitches torefmode, so bindings become shared references. - Matching a
&mut Tswitches toref mutmode, so bindings become mutable references. - The mode stays in effect for every nested pattern.
This is why match &msg { Message::Text(s) => ... } gives s: &String without any extra syntax.
| Scrutinee | Pattern | Type of `s` | Original value afterward |
|---|---|---|---|
| `msg` | `Text(s)` | `String` | Partially moved |
| `&msg` | `Text(s)` | `&String` | Intact |
| `&mut msg` | `Text(s)` | `&mut String` | Intact, mutated through `s` |
| `msg` | `Text(ref s)` | `&String` | Intact |
Mutating through a pattern
To change data inside an enum, match on a mutable reference. The bindings become &mut, and you write through them with *.
enum Counter {
Count(u32),
Done,
}
fn bump(c: &mut Counter) {
match c {
Counter::Count(n) => *n += 1,
Counter::Done => {}
}
}
fn main() {
let mut c = Counter::Count(1);
bump(&mut c);
bump(&mut c);
if let Counter::Count(n) = c {
println!("{n}");
}
}This prints 3. The final if let matches by value, but n is a u32, which is Copy, so nothing is moved out of c.
Moving out from behind a reference
The most common ownership error with patterns is trying to move a non-Copy part out of something you only borrow. Take a method with &self that matches a field directly:
match self.nickname {
Some(n) => n,
None => "anonymous".to_string(),
}The compiler rejects this with error E0507, "cannot move out of self.nickname as enum variant Some which is behind a shared reference". The pattern Some(n) would move the String out of a struct that the method does not own. There are three fixes, and the right one depends on what you need:
- Borrow it: match on
&self.nickname, sonis a&String. - Convert the option:
self.nickname.as_ref()turns&Option<String>intoOption<&String>, andas_mut()does the same for&mut. - Take ownership explicitly:
self.nickname.take()on a&mutreplaces the field withNoneand returns the old value.
struct Profile {
nickname: Option<String>,
}
impl Profile {
fn label(&self) -> &str {
match &self.nickname {
Some(n) => n.as_str(),
None => "anonymous",
}
}
fn take_nickname(&mut self) -> Option<String> {
self.nickname.take()
}
}
fn main() {
let mut p = Profile {
nickname: Some("ace".to_string()),
};
println!("{}", p.label());
println!("{:?}", p.take_nickname());
println!("{}", p.label());
}The output is ace, Some("ace"), then anonymous.
Explicit `ref`, `ref mut`, and `&` patterns
Before default binding modes existed, you had to write ref yourself. It still works and still has a use: Message::Text(ref s) borrows the string even when the scrutinee is an owned value. In modern code you will usually write match &msg instead, which is shorter and applies to every binding at once.
The & pattern goes the other way. It matches a reference and removes it, so the binding gets the value behind it. This is useful for Copy data:
fn main() {
let scores = vec![Some(3), None, Some(9)];
let mut total = 0;
for entry in &scores {
if let &Some(n) = entry {
total += n;
}
}
println!("{total}");
}Here entry is &Option<i32>. The pattern &Some(n) removes the reference and binds n as an i32 copy. Without the &, n would be &i32. That still works with += here, but it fails in places that need an owned i32. The & pattern requires the target to be Copy. You cannot write &Some(s) against a &Option<String>, because it would move the String out from behind the reference.
Choosing a mode
- Match on
&valueor&mut valuewhen you only need to read or change the contents and want to keep using the value. - Match on
valuewhen you are done with it and want the contents. The usual cases are consuming an enum, or readingCopyfields. - Prefer
as_ref(),as_mut(), andtake()when the value sits in a field behind a reference. - If the error mentions "behind a shared reference", you are trying to move. Switch to a borrow.
- If the error says "borrow of partially moved value", an earlier pattern moved something you still need. Borrow in that pattern, or bind only the fields you need.
Exercise
A method fn describe(&self) -> String on a struct with field title: Option<String> contains match self.title { Some(t) => t, None => String::new() }. It fails with E0507. Give two fixes that keep &self, and say what each one does to self.title.
Show answer
Fix 1: match on &self.title and return t.clone() in the Some arm, because t is a &String. Fix 2: write self.title.clone().unwrap_or_default(), or self.title.as_deref().unwrap_or("").to_string(). In every version self.title is only borrowed, so it stays intact. Taking the string without cloning requires &mut self and self.title.take(), which leaves None behind.
Exercise
After let (first, _) = pair; where pair is (String, String), can you use pair.1? What if the pattern were (first, _second)?
Show answer
Yes for (first, _), because _ does not bind, so only pair.0 moves. No for (first, _second), because _second is a real binding that moves pair.1.