Match Mutable Bindings To Mutate In Place
Matching on &mut hands each arm a mutable borrow, letting match arms patch enum payloads and Option values without rebuilding them.
Code
#[derive(Debug)]
enum Job {
Pending { retries: u32 },
Done,
}
fn main() {
let mut queue = vec![
Job::Pending { retries: 0 },
Job::Done,
Job::Pending { retries: 2 },
];
// Borrow the whole Vec: match &mut hands each arm an exclusive borrow of the field, edited in place
for job in queue.iter_mut() {
match job {
Job::Pending { retries } => {
*retries += 1;
if *retries >= 3 {
*job = Job::Done;
}
}
Job::Done => {}
}
}
println!("{:?}", queue);
// Option works the same: if let binds &mut, the None arm stays untouched
let mut speed: Option<u32> = Some(70);
if let Some(current) = speed.as_mut() {
*current += 10;
}
println!("speed: {:?}", speed);
let mut absent: Option<u32> = None;
if let Some(current) = absent.as_mut() {
*current += 10;
}
println!("absent unchanged: {:?}", absent);
}How the snippet works
Count the function main as the entire surface area of Match Mutable Bindings To Mutate In Place.
Iteration happens inside for job in queue.iter_mut() — everything outside it runs once. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
Using it
Output lines are prefixed (speed:, absent unchanged:), making each step’s effect easy to spot.
Key statements
if let Some(current) = absent.as_mut() {
*current += 10;
}
if let Some(current) = speed.as_mut() {
*current += 10;
}
let mut speed: Option<u32> = Some(70);
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Match Mutable Bindings To Mutate In Place print when run?
- No setup needed: run the file and look for labeled lines like `speed:`, `absent unchanged:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.