官术网_书友最值得收藏!

Maps

Maps are key-value data structures, where both the key and the value can be of any type. They're similar to hashes in Ruby and dictionaries in Python. To create a map, you enclose your key-value pairs in %{}, and put a => between the key and the value, as we can see in the following snippet:

iex> %{:name => "Gabriel", :age => 1}
%{age: 1, name: "Gabriel"}

In this case, the keys are both of the same type, but this isn't required. If your keys are atoms, you can use the following syntax to make the map declaration simpler:

iex> %{name: "Gabriel", age: 1}
%{age: 1, name: "Gabriel"}

To access the value associated with a certain key, put the key inside square brackets in front of the map:

iex> map = %{name: "Gabriel", age: 1}
%{age: 1, name: "Gabriel"}
iex> map[:name]
"Gabriel"

As with the map declaration, when the key is an atom, we have some syntatic sugar on top of it:

iex> map.name
"Gabriel"
When you try to fetch a key that doesn't exist in the map, a KeyError error will be raised when using the map.key syntax unlike the map[key] syntax, which will return nil.

To update a key in a map, you can use %{map | key => new_value}. If the key is an atom, we can use the same notation described previously:

iex> %{map | age: 2}
%{age: 2, name: "Gabriel"}
If you're coming from an object-oriented programming background, you may instinctively use the following syntax to change the value of a key: map[key] = new_value. Remember that in Elixir all types are immutable and you never operate on the data structure itself but always on a copy of it.

This will only work for keys that already exist in the map—this constraint allows Elixir to optimize and reuse the fields list when updating a map. If you want to insert a new key, use the put function from the Map module:

iex> Map.put(map, :gender, "Male")
%{age: 1, gender: "Male", name: "Gabriel"}

As with all other types, in the official documentation, at https://hexdocs.pm/elixir/Map.html, you can find a pretty detailed reference on what you can do with maps.

主站蜘蛛池模板: 东乡| 赣榆县| 徐州市| 枞阳县| 三门县| 高州市| 肇东市| 措勤县| 万全县| 瓦房店市| 濮阳县| 宁陵县| 罗平县| 阿瓦提县| 家居| 铅山县| 襄樊市| 咸丰县| 罗山县| 光泽县| 沙田区| 昌平区| 洛南县| 克什克腾旗| 潍坊市| 广安市| 桑植县| 叶城县| 手游| 米脂县| 台湾省| 遂溪县| 高平市| 绵竹市| 富平县| 剑河县| 上高县| 新竹市| 当涂县| 浮梁县| 海门市|