@@ -212,6 +212,49 @@ some_args = (x=100, y=x+1000) ->
212212 print x + y
213213```
214214
215+ ### Argument Destructuring
216+
217+ An argument can be written as a table literal to
218+ [ destructure] ( #destructuring_assignment ) the value that is passed in. The names
219+ in the table literal become local variables in the body of the function.
220+
221+ ``` moon
222+ send_message = ({:sender, :recipient, :body}) ->
223+ print "#{sender} -> #{recipient}: #{body}"
224+
225+ send_message {
226+ sender: "leaf"
227+ recipient: "world"
228+ body: "hello"
229+ }
230+ ```
231+
232+ Any pattern that can be used in a destructuring assignment can be used here,
233+ including positional names and nested tables:
234+
235+ ``` moon
236+ draw = ({label, pos: {x, y}}) ->
237+ print label, x, y
238+
239+ draw { "origin", pos: {0, 0} }
240+ ```
241+
242+ Destructured arguments can be mixed with regular arguments, argument defaults,
243+ and ` ... ` :
244+
245+ ``` moon
246+ render = (name, {:width, :height} = {width: 100, height: 50}, ...) ->
247+ print name, width, height, ...
248+ ```
249+
250+ Using a fat arrow, the pattern can assign directly to properties of the object.
251+ This is convenient for a constructor:
252+
253+ ``` moon
254+ class Point
255+ new: ({x: @x, y: @y}) =>
256+ ```
257+
215258### Considerations
216259
217260Because of the expressive parentheses-less way of calling functions, some
@@ -1420,6 +1463,13 @@ extract by mixing the syntax:
14201463{:mix, :max, random: rand } = math
14211464```
14221465
1466+ The extracted values don't have to be assigned to plain names. Anything that can
1467+ go on the left hand side of an assignment works, like properties and indexes:
1468+
1469+ ``` moon
1470+ {x: @x, y: obj.y, z: obj["z"]} = point
1471+ ```
1472+
14231473### Destructuring In Other Places
14241474
14251475Destructuring can also show up in places where an assignment implicitly takes
@@ -1439,6 +1489,17 @@ for {left, right} in *tuples
14391489We know each element in the array table is a two item tuple, so we can unpack
14401490it directly in the names clause of the for statement using a destructure.
14411491
1492+ Destructuring can also be mixed with regular names when assigning multiple
1493+ values at once:
1494+
1495+ ``` moon
1496+ num, {:message} = get_result!
1497+ print num, message
1498+ ```
1499+
1500+ Function arguments can be destructured as well, see [ Argument
1501+ Destructuring] ( #argument_destructuring ) .
1502+
14421503
14431504## Function Stubs
14441505
0 commit comments