Conceptcore
Destructuring assignment
Also called destructuring, destructuring assignment, unpacking, tuple unpacking, iterable unpacking, parallel assignment, multiple assignment, deconstruction, pattern binding.
Destructuring assignment binds several names from the parts of one composite value, such as a tuple, an array or an object. The pattern on the left can skip parts, collect the rest and nest.
- Applies to
- core-languages
Idea
A value often has parts: a point has x and y, a row has a name and some scores. Destructuring takes the parts out into names in one step. "The destructuring syntax is a JavaScript syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables."1 In Python it is called unpacking:
point = (3, 4)
x, y = point
print(x, y)
name, *scores = ["Ada", 90, 85, 77]
print(name, scores)
3 4
Ada [90, 85, 77]
Without destructuring, the program reads each part with an index: x = point[0] and y = point[1].
How it works
A pattern on the left side. The left side of the assignment has the shape of the value. Rust says: "Destructuring breaks up a value into its component pieces. The syntax used is almost the same as when creating such values."2 A tuple pattern (a, b) takes a pair apart, and an object pattern { name, age } takes two properties.
By position or by name. Tuples and arrays are taken apart by position: the first name gets the first item. Objects, structs and records are taken apart by name: JavaScript const { width, height } = box reads the properties width and height, in any order. In C#, "A deconstruction assigns the individual parts of a value — its components — to multiple variables in a single operation."3 A class can define a Deconstruct method to say what its parts are.
The count must match. In Python, a pattern with a starred name takes the other items: "The object must be an iterable with at least as many items as there are targets in the target list, minus one."4 Without a starred name, the counts must be equal, and a, b = [1, 2, 3] raises ValueError. JavaScript does not check: a missing item gives undefined, and extra items are ignored.
Parallel assignment. Destructuring of a tuple that the program writes on the right side assigns several names at once. Many languages allow it, such as APL, Common Lisp, Go, JavaScript, Julia, PHP, Lua, Perl, Python, Ruby and PowerShell5. The right side is computed first, so a, b = b, a swaps two values.
Defaults, skips, rest and nesting. In JavaScript, "Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined."1 A name such as _, or an empty place in [a, , c], skips a part. A rest name collects the other items: "For array destructuring, it collects remaining elements of the iterable into a new array"1. A pattern can contain other patterns, such as [[a, b], c].
Patterns in other places. The same patterns appear in parameters, in for loops such as for (key, value) in pairs, and in match or switch. Java has record patterns in instanceof and switch: "A record pattern consists of a ReferenceType and a component pattern list containing component patterns, if any."6 C++ has structured bindings, which "Binds the specified names to subobjects or elements of the initializer"7.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the array and object patterns of JavaScript, and the compiler checks the types of the parts. No example file exists. |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | Val (a, b) = pair calls the functions component1 and component2, which data classes, pairs and map entries have. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query selects columns by name, with no assignment of the parts of a value. |
| Bash | Idiom | Read -r a b <<< "$line" splits a line into words and assigns them to names. No example file exists. |
| PowerShell | Native | $a, $b = 1, 2 assigns several values at once, and the last name collects the rest. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup, with no variables. |
| CSS | Does not apply | CSS has no variables to bind. |
| Regular expressions | Idiom | Capture groups take the parts of a match, and named groups give the parts names. |
| Language | Verdict | Destructuring |
|---|---|---|
| Python | native | a, b = pair, first, *rest = items, nested targets, and patterns in match |
| JavaScript | native | array patterns [a, b] and object patterns { a, b }, with defaults, renames and rest |
| TypeScript | native | the patterns of JavaScript, with types |
| Java | native | record patterns in instanceof and switch |
| Kotlin | native | val (a, b) = pair with componentN functions, for data classes and pairs |
| C# | native | var (a, b) = tuple, Deconstruct methods, and discards _ |
| Go | idiom | a, b := f() for several return values, and parallel assignment a, b = b, a; no patterns for structs or slices |
| Rust | native | patterns in let, match, if let and parameters, for tuples, structs, enums and slices |
| C | absent | no destructuring; read each member of a struct |
| C++ | native | structured bindings auto [a, b] = pair |
| Bash | idiom | read -r a b <<< "$line" splits a line into names |
| PowerShell | native | $a, $b = 1, 2, and the last name collects the rest |
| SQL | n/a | a query selects columns by name, with no assignment of parts |
| Regex | idiom | capture groups take the parts of a match, and named groups give them names |
| HTML | n/a | HTML is markup, with no variables |
| CSS | n/a | CSS has no variables to bind |
C++. A structured binding is an alias, not a copy: "Like a reference, a structured binding is an alias to an existing object."7 With auto&, a change through the name changes the original object.
pairs = [("a", 1), ("b", 2)]
for key, value in pairs:
print(key, value)
(a, b), c = (1, 2), 3
print(a, b, c)
first, *_, last = range(10)
print(first, last)
try:
x, y = [1, 2, 3]
except ValueError as e:
print(type(e).__name__)
a 1
b 2
1 2 3
0 9
ValueError
- Verdict: native. Any iterable can be unpacked into a list of targets, in an assignment, a
forloop or awithstatement. Targets can nest, and one starred target takes the other items as a list. When the counts do not match, Python raisesValueError.
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <utility>
struct Point {
int x;
int y;
};
std::pair<int, int> divmod(int n, int d) {
return {n / d, n % d};
}
int main() {
auto [q, r] = divmod(17, 5);
std::cout << q << " " << r << "\n";
Point p{3, 4};
auto& [x, y] = p;
x = 10;
std::cout << p.x << " " << y << "\n";
auto [cx, cy] = p;
cx = 99;
std::cout << p.x << " " << cx << " " << cy << "\n";
std::map<std::string, int> ages{{"Ada", 36}, {"Alan", 41}};
for (const auto& [name, age] : ages) {
std::cout << name << " " << age << "\n";
}
auto [a, b, c] = std::tuple{1, 'z', 2.5};
std::cout << a << b << c << "\n";
}
3 2
10 4
10 99 4
Ada 36
Alan 41
1z2.5
- Verdict: native. A structured binding gives names to the members of a struct, the items of an array, or the elements of a pair or tuple. With
auto&the names refer to the original object, and withautothey refer to a copy.
public class Main {
record Point(int x, int y) {}
record Line(Point from, Point to) {}
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Square(double side) -> side * side;
};
}
public static void main(String[] args) {
Object o = new Point(3, 4);
if (o instanceof Point(int x, int y)) {
System.out.println(x + y);
}
Line line = new Line(new Point(0, 0), new Point(2, 5));
if (line instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) {
System.out.println((x2 - x1) + " " + (y2 - y1));
}
System.out.println(area(new Square(3)));
}
}
7
2 5
9.0
- Verdict: native. A record pattern takes a record apart into its components, in
instanceofand inswitch. Patterns can nest, andvartakes the type of the component. Java has no destructuring of arrays or of other classes.
#include <stdio.h>
struct divmod {
int q;
int r;
};
static struct divmod divide(int n, int d) {
struct divmod res = { n / d, n % d };
return res;
}
int main(void) {
struct divmod res = divide(17, 5);
int q = res.q;
int r = res.r;
printf("%d %d\n", q, r);
int a = 1, b = 2;
int tmp = a;
a = b;
b = tmp;
printf("%d %d\n", a, b);
return 0;
}
3 2
2 1
- Verdict: absent. C has no destructuring and no parallel assignment. A function returns a struct, and the caller reads each member. A swap needs a temporary variable.
using System;
var (q, r) = DivRem(17, 5);
Console.WriteLine($"{q} {r}");
var p = new Point(3, 4);
var (x, _) = p;
Console.WriteLine(x);
var (value, unit) = new Temperature(21, "C");
Console.WriteLine($"{value} {unit}");
int a = 1, b = 2;
(a, b) = (b, a);
Console.WriteLine($"{a} {b}");
static (int, int) DivRem(int n, int d) => (n / d, n % d);
record Point(int X, int Y);
class Temperature(int degrees, string unit)
{
public void Deconstruct(out int value, out string scale)
{
value = degrees;
scale = unit;
}
}
3 2
3
21 C
2 1
- Verdict: native. A tuple is deconstructed into new variables or into existing ones. A positional record gets a
Deconstructmethod from the compiler, and any class can define one. The discard_drops a part.
const [a, , c = 30, ...rest] = [10, 20, undefined, 40, 50];
console.log(a, c, rest);
const { name, age: years = 0, ...other } = { name: "Ada", city: "London", role: "dev" };
console.log(name, years, other);
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x, y);
10 30 [ 40, 50 ]
Ada 0 { city: 'London', role: 'dev' }
2 1
- Verdict: native. An array pattern takes items by position, and an empty place skips one. An object pattern takes properties by name, and
age: yearsreadsageinto the nameyears. A default replacesundefined, and a rest element collects the other items or properties.
package main
import "fmt"
type point struct{ x, y int }
func divmod(a, b int) (int, int) {
return a / b, a % b
}
func main() {
q, r := divmod(17, 5)
fmt.Println(q, r)
_, r2 := divmod(20, 6)
fmt.Println(r2)
a, b := 1, 2
a, b = b, a
fmt.Println(a, b)
p := point{3, 4}
x, y := p.x, p.y
fmt.Println(x, y)
m := map[string]int{"a": 1}
v, ok := m["b"]
fmt.Println(v, ok)
}
3 2
2
2 1
3 4
0 false
- Verdict: idiom. Go assigns several values at once: the results of a call, or a list of expressions such as
a, b = b, a. The blank identifier_drops a value. Go has no patterns for structs or slices, so each field is read by name.
struct Point {
x: i32,
y: i32,
}
fn main() {
let (q, r) = (17 / 5, 17 % 5);
println!("{q} {r}");
let p = Point { x: 3, y: 4 };
let Point { x, y: height } = p;
println!("{x} {height}");
let items = [1, 2, 3, 4, 5];
let [first, .., last] = items;
println!("{first} {last}");
let pairs = vec![("a", 1), ("b", 2)];
for (key, value) in &pairs {
println!("{key}={value}");
}
let (mut a, mut b) = (1, 2);
(a, b) = (b, a);
println!("{a} {b}");
}
3 2
3 4
1 5
a=1
b=2
2 1
- Verdict: native. A
lettakes a pattern, so tuples, structs and arrays are taken apart where they are declared.y: heightbinds the fieldyto the nameheight, and..skips the other items. The same patterns work infor,matchand parameters, and an assignment can also destructure into existing variables.
Variations and related ideas
- Swap.
a, b = b, ain Python and[a, b] = [b, a]in JavaScript swap two values without a temporary variable. - Several return values. A function returns a tuple, and the caller destructures it:
q, r = divmod(17, 5). - Pattern matching. Destructuring is the binding part of pattern matching. A
matchalso tests the shape and picks a branch. - Ignore parts.
_takes a part and drops it, in Python, Go, Rust, C# and other languages.
Pitfalls
- A default for null. In JavaScript, a default value replaces
undefinedbut notnull. "It is not used if the property has value null."1
This code runs but gives a wrong answer on purpose.
const { size = 10 } = { size: null };
console.log(size);
const { limit = 10 } = {};
console.log(limit);
null
10
Use const size = options.size ?? 10; when null also means "no value".
- A count that does not match. Python raises
ValueErrorwhen the counts differ. JavaScript and Lua fill the gap withundefinedornil, so the error shows up later. - A copy or an alias. In C++,
auto [a, b] = pcopiespand binds names to the copy, butauto& [a, b] = pbinds names topitself. In Rust and JavaScript, destructuring of an object copies or moves its parts. - A statement that starts with a brace. In JavaScript,
{ a, b } = obj;withoutconstorletis a block, not a pattern. Write({ a, b } = obj);.
Cost
Destructuring costs the same as a read of each part. In a compiled language, auto [q, r] = f() is the same code as two reads of the members. Python builds no new objects for the targets, but a starred name makes a new list.
History
Parallel assignment is old: "it was introduced in CPL in 1963, under the name simultaneous assignment"5. Later, many languages added destructuring of tuples, arrays and objects. C++ added structured bindings in C++177.
References
- Destructuring, MDN Web Docs, Description; Default value; Rest properties and rest elements
- Patterns, The Rust Reference, patterns.destructure
- Deconstruct tuples and other types, C# guide, Introduction
- Simple statements, The Python Language Reference, 7.2 Assignment statements
- Assignment (computer science), Wikipedia, Parallel assignment
- Chapter 14, Blocks, Statements, and Patterns, The Java Language Specification, Java SE 25, 14.30.1 Kinds of Patterns
- Structured binding declaration, cppreference.com (C++), Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag ZVSAC3 Edit this page History Report an error Markdown