- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 366字
- 2021-08-05 10:42:45
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"
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"}
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.
- 程序員修煉之道:程序設計入門30講
- Reporting with Visual Studio and Crystal Reports
- 移動UI設計(微課版)
- 騰訊iOS測試實踐
- 自己動手實現Lua:虛擬機、編譯器和標準庫
- Java入門很輕松(微課超值版)
- Python高級編程
- Python機器學習實戰
- PHP+MySQL網站開發項目式教程
- 零基礎輕松學SQL Server 2016
- 好好學Java:從零基礎到項目實戰
- Statistical Application Development with R and Python(Second Edition)
- Advanced UFT 12 for Test Engineers Cookbook
- Mastering HTML5 Forms
- Qt 4開發實踐