In Elixir, there are three types of key-value constructs:
[key: value]
.%{key: value}
or %{key=> value}
.%structname{key: value}
.Dynamically accessing keys of an associative data structure like keyword lists or maps is called key-based access. Elixir gives two mechanisms to access data by key:
Bracket-based access is used to access keys in dynamic structures such as maps and keyword lists.
The syntax is data[key]
.
If the key exists, it returns the corresponding value. Otherwise, it returns _nil_
or nothing.
# Keyword lists keywords = [x: 5, y: 2, z: 10] IO.puts "key exists and the value is" IO.puts keywords[:x] # Map map = %{x: 5, y: 2, z: 10} IO.puts "key exists and the value is" IO.puts map[:z]
Dot-based syntax is limited to accessing structs and atom fields in maps.
The syntax is data.value
.
If the key exists, it returns the value. Otherwise, it throws an error.
# Struct defmodule Emp do defstruct name: "BOB", age: 37 end defmodule Main do def main do data = %Emp{} IO.puts "key exists and the value is" IO.puts data.name end end Main.main # Map map = %{x: 5, y: 2, z: 10} IO.puts "key exists and the value is" IO.puts map.z
RELATED TAGS
CONTRIBUTOR
View all Courses