Create a Map with an Integer Key

烈酒焚心 提交于 2019-12-11 04:06:03

问题


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)

回答1:


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" }


来源:https://stackoverflow.com/questions/43220630/create-a-map-with-an-integer-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!