Destructuring
Do supports destructuring data in let, bind, and for.
let Destructuring
Destructure arrays and similar sequences by listing multiple names:
By default, the pattern must exhaustively match the entire structure or an
error will result. Use ... to capture surplus items instead. The specified
variable will be bound to an iterator over them.
Specify nothing after ... to simply ignore surplus items:
Destructure dictionaries and similar key/value structures with keyword patterns:
Mixed positional/key destructuring is also possible, with the semantics depending on the structure. For dictionaries, positional patterns bind incrementing integer keys:
bind
bind is similar to let but takes the scrutinee (the value to destructure)
first and provides the destructuring pattern in vertical layout. This is
useful when the pattern is more complex than what you're destructuring. It also
supports default values for missing elements:
bind {1, foo: false, 2, bar: nil}
- a
- b
:foo
:bar
assert_eq $a 1
assert_eq $b 2
assert_eq $foo false
assert_eq $bar nil
Default Values in bind
Positional defaults:
bind []
- a = 1
- b = 2
assert_eq $a 1
assert_eq $b 2
bind [false]
- a = 1
- b = 2
assert_eq $a false
assert_eq $b 2
Keyword defaults:
bind {}
:foo = 42
assert_eq $foo 42
bind {foo: nil}
:foo = 42
assert_eq $foo nil # nil is a present value, not missing
Destructuring in for
Destructure elements during iteration: