Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

elixir
key based
accessors

What are key-based accessors in Elixir?

Azeem Ashraf

Overview

In Elixir, there are three types of key-value constructs:

  • Keyword lists: This is a list of key-value pairs where the first element is an atom and the second element is a value. They are written as [key: value].
  • Maps: This is the data structure to store key-value pairs. They are written as %{key: value} or %{key=> value}.
  • Structs: This is a pre-determined set of map keys. They are written as %structname{key: value}.

Key-based accessors

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:

  1. Bracket-based access
  2. Dot-based syntax

Bracket-based access

Bracket-based access is used to access keys in dynamic structures such as maps and keyword lists.

Syntax

The syntax is data[key].

Return value

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

Dot-based syntax is limited to accessing structs and atom fields in maps.

Syntax

The syntax is data.value.

Return 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

elixir
key based
accessors

CONTRIBUTOR

Azeem Ashraf
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring