What is the difference between ":" and "=>" in map declaration?

When declaring a map, I noticed that there are two ways to specify a key/value pair.

① m1 = %{:a => 1, 2 => :b}
② m2 = %{a: 1, b: 2}

Both of these contain the key of :a (atom whose value is “a”), and such, the value can be retrieved using the same syntax: m1[:a] and m2[:a].

Is there a difference between using the => and the :? I noticed you also cannot mix them when declaring a map…

1 Like

you can use : only with atom-keys.

1 Like

The : version is syntax sugar for atom keys, to make writing maps a bit shorter/easier. You can actually use both syntaxes within one map, but only as long as all the pairs using the syntax sugar are defined at the trailing end within the map. Same goes for keyword lists syntax sugar btw.

2 Likes