Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Map with an Integer Key

I want to create a map with a key of type integer, but this doesn't work:

iex(1)> a = %{3: "fdsfd"}
** (SyntaxError) iex:1: unexpected token: ":" (column 8, codepoint U+003A)

iex(1)> a = %{:3 => "fdsfd"}
** (SyntaxError) iex:1: unexpected token: ":" (column 7, codepoint U+003A)
like image 836
Otoma Avatar asked Mar 09 '23 10:03

Otoma


1 Answers

To use an Integer as a key, simply use it like this:

map = %{ 3 => "value" }

:3 is an invalid value in Elixir; atoms are neither Strings or Integers in Elixir, they are constants where their name is their value. To use a key with only 3 as an atom, you would have to use this:

map = %{ :"3" => "value" }
like image 143
Sheharyar Avatar answered Mar 20 '23 06:03

Sheharyar