Skip to content
Maps
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

Maps are key-value collections. Two literal forms — atom keys (most common) get a shorthand:

user = %{name: "Alice", age: 30}      # atom keys
ages = %{"Alice" => 30, "Bob" => 25}   # arbitrary keys (rocket form)

IO.puts user.name              # 'Alice' (atom-keys only)
IO.puts user[:name]            # 'Alice' (works for any key)
IO.puts ages["Alice"]          # 30

Maps are immutable. To "update" you create a new map. The %{map | key: new_value} syntax updates a key (and errors if the key doesn't exist). Map.put adds or updates:

user = %{name: "Alice", age: 30}
older = %{user | age: 31}
updated = Map.put(user, :email, "[email protected]")

For missing-key handling, Map.get(m, k, default) is safer than m[k].

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…