Maps
Maps are a type of data structures also known as dictionaries or associative arrays. To read the value associated with a given key use the `maps:get/2` function. Trying to get a non existing key will trow an exception. A solution is to provide a default value. To prevent exceptions in case a key is not found you can use `maps:find/2`. For more information about the `maps` module, please consult the official docs
-module(map). -compile([export_all]). write(String, Value) -> io:format("~p = ~p~n", [String, Value]). run() -> M1 = #{name => "Joe Doe", age => 25}, write("Map", M1), write("Name", maps:get(name, M1)), write("Degree", maps:get(degree, M1, defaultdegree)), Keyname = randomkey, case maps:find(Keyname, M1) of {ok, Value} -> write("Found value", Value); error -> write("No value found for key", Keyname) end, ok.
1> c(map). {ok,map} 2> map:run(). "Map" = #{age => 25,name => "Joe Doe"} "Name" = "Joe Doe" "Degree" = defaultdegree "No value found for key" = randomkey ok 50>
Next: Guards →