0
0
Rustprogramming~10 mins

Destructuring patterns in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Destructuring patterns
Start with a value
Apply destructuring pattern
Extract parts into variables
Use extracted variables
End
Destructuring patterns break a value into parts and assign them to variables step-by-step.
Execution Sample
Rust
let (x, y) = (10, 20);
println!("x = {}, y = {}", x, y);
This code splits a tuple into two variables x and y, then prints them.
Execution Table
StepActionPatternValueVariables Assigned
1Start with tuple value(x, y)(10, 20)none
2Match pattern to value(x, y)(10, 20)x = 10, y = unassigned
3Assign y from tuple(x, y)(10, 20)x = 10, y = 20
4Use variablesN/AN/APrint x=10, y=20
5EndN/AN/AVariables x=10, y=20 in scope
💡 All parts of the tuple matched and assigned, execution ends.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
xunassigned101010
yunassignedunassigned2020
Key Moments - 2 Insights
Why is y unassigned after step 2 but assigned after step 3?
Step 2 starts matching the pattern but only assigns x first; y is assigned in step 3 as the pattern matches the second tuple element (see execution_table rows 2 and 3).
What happens if the pattern and value lengths don't match?
Rust will give a compile-time error because the destructuring pattern must match the value structure exactly (not shown here but important to know).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 3?
A10
B20
Cunassigned
DNone
💡 Hint
Check the 'Variables Assigned' column in row 3 of the execution_table.
At which step are both x and y assigned values?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Look at the 'Variables Assigned' column to see when both variables have values.
If the tuple was (10, 20, 30), what would happen to the destructuring pattern (x, y)?
Ax=10, y=20, 30 ignored
Bx=10, y=30
CCompile-time error due to mismatch
Dx=20, y=30
💡 Hint
Rust requires pattern and value to match exactly; extra elements cause errors.
Concept Snapshot
Destructuring patterns let you split complex values into parts.
Syntax: let (a, b) = (1, 2);
Each pattern part matches a value part.
All parts must match exactly.
Variables get assigned in order.
Use destructuring to simplify code.
Full Transcript
This visual trace shows how destructuring patterns work in Rust. We start with a tuple (10, 20). The pattern (x, y) matches this tuple. Step 2 assigns x to 10, step 3 assigns y to 20. After both assignments, we can use x and y as separate variables. If the pattern and value don't match in size, Rust will give an error. This helps break down values simply and safely.