You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: pages/docs/manual/latest/pattern-matching-destructuring.mdx
+14-8Lines changed: 14 additions & 8 deletions
Original file line number
Diff line number
Diff line change
@@ -48,14 +48,6 @@ type result =
48
48
| Success(string)
49
49
let myResult = Success("You did it!")
50
50
let Success(message) = myResult // "You did it!" assigned to `message`
51
-
52
-
// Array
53
-
let myArray = [1, 2, 3]
54
-
let [item1, item2, _] = myArray // 1 assigned to `item1`, 2 assigned to `item2`, 3rd item ignored
55
-
56
-
// List
57
-
let myList = list{1, 2, 3}
58
-
let list{head, ...tail} = myList // 1 assigned to `head`, `list{2, 3}` assigned to tail
59
51
```
60
52
```js
61
53
var student1 = {
@@ -138,6 +130,20 @@ var n = "John";
138
130
139
131
</CodeTab>
140
132
133
+
You _can_ in theory destructure array and list at the top level too:
134
+
135
+
```res
136
+
let myArray = [1, 2, 3]
137
+
let [item1, item2, _] = myArray
138
+
// 1 assigned to `item1`, 2 assigned to `item2`, 3rd item ignored
139
+
140
+
let myList = list{1, 2, 3}
141
+
let list{head, ...tail} = myList
142
+
// 1 assigned to `head`, `list{2, 3}` assigned to tail
143
+
```
144
+
145
+
But the array example is **highly disrecommended** (use tuple instead) and the list example will error on you. They're only there for completeness' sake. As you'll see below, the proper way of using destructuring array and list is using `switch`.
146
+
141
147
## `switch` Based on Shape of Data
142
148
143
149
While the destructuring aspect of pattern matching is nice, it doesn't really change the way you think about structuring your code. One paradigm-changing way of thinking about your code is to execute some code based on the shape of the data.
0 commit comments