Destructuring is a Clojure-specific way of variable assignment (binding in Clojure).
It enables us to bind:
- each element in a vector to corresponding variables - case 1
- one element in a vector to a variable - case 2
- each value in a map (key-value pairs) to the corresponding variables - case 3
in a single binding.
Let’s try some simple examples:
As we see above, destructuring has two kinds of bindings:
- vector binding forms
- map binding forms
-
destructuring-able types: whatever nth
function can be applied
- example: vector, list, seq, string
-
works like pattern matching
-
optional binding rules, &
, :as
See more examples:
-
destructuring-able types: whatever associative types
-
works looking at key
-
optional binding rules, :keys
, :as
, :or
-
:keys
convention applies to avoid wordiness. variable names are key names without :
-
:as
binds entire key-value pairs to a given variable
-
:or
defines default values for specified keys
See more examples:
Where destructuring is used
-
let bindings
-
function parameter lists
All examples of destructuring here are in let bindings.
However, destructuring can also be used in function parameter lists.
References