# Tables and Structs

Recall:

 struct: immutable `{:a 1 :b 2}` table: mutable `@{:a 1 :b 2}`
``````(def t @{:a 1 :b 2 :c 3})

# Can also make a table with:
(table :a 1 :b 2 :c 3)
# or
(def a [:a 1 :b 2 :c 3]
(table ;a)

(length t)  #=> 3

# Unlike arrays, tables cannot have `nil` as a key or a value.

(keys t)    #=> @[:c :a :b]
(values t)  #=> @[ 3  1  2]

(get t :c)  #=> 3
(t :c)      # same
(get t :x)  #=> nil

(put t :x 7)  # Mutates `t`, and also returns it.
@{:c 3 :x 7 :a 1 :b 2}

# Can also set/add values in a table using `set`:
(set (t :a) 88)  #=> 88
# `t` is now `@{:c 3 :x 7 :a 88 :b 2}`

# Add a value to the table.
(set (t :z) 99)  # @{:a 88 :b 2 :c 3 :x 7 :z 99}

# Remove value (here, `:z`) from a table:
(put t :z nil)   #=> the mutated array
(set (t :z) nil) #=> nil

# Nested data structures.
(def t @{:a @[1 2 @{:x 1}] :b "yo"})
# If you want to change that :x value to a 3 ... Note:
# `(t :a)`           is an array.
# `((t :a) 2)`       is that table `@{:x 1}`.
# `(((t :a) 2) :x)`  is that 1.
# So, both of these work:
(put ((t :a) 2) :x 3)    # First arg is the ds `put` operates on.
#    ^^^^^^^^^^
(set (((t :a) 2) :x) 3)  # First arg is the value to set.
#    ^^^^^^^^^^^^^^^
# `t` is now `@{:a @[1 2 @{:x 3}] :b "yo"})`
# Note, you can increment it like so:
(++ (((t :a) 2) :x))  #=> 4, and
# `t` is now `@{:a @[1 2 @{:x 4}] :b "yo"})`

(pairs t)  # Returns an array of 2-element key-value tuples.

(defn foo [x] (* x 4))
#                    @{:a 88 :b 2 :c  3 :x 7 :z 99}
(update t :c foo)  # @{:a 88 :b 2 :c 12 :x 7 :z 99}

(zipcoll [:a :b :c] [1 2 3])  #=> @{:c 3 :a 1 :b 2}

(merge t1 t2)          # Merges and returns a new table.
(merge-into t1 t2 t3)  # Merges into and modifies `t1`.

# Since tables are mutable:
(= t1 t2)  # Only checks if they point to the same table.

# But you also have:
(deep= t1 t2)  # Recurs down, checking for equality.``````

Notes:

• `table/clone` doesn’t copy everything deeply

For more examples that involve arrays and maps together, see the more working with data structures section.

For official docs, see: