LoginSignup
11
0

Elixir Mapの参照方法は二種類。必須の時とオプションの時で使い分けよう

Last updated at Posted at 2023-12-19

Mapの値参照方法

Mapの値参照には、[]と. を使った二種類の書き方があります。
この二つ同じだと思ってたんですが、違いがありました。

記述 キーが存在しない時の動作
point[:z] nilが返される。エラーにならない
point.z エラーになる

例をみてみましょう

iex(5)> point = %{x: 10, y: 20}
%{x: 10, y: 20}
iex(6)> point[:x]
10
iex(7)> point[:y]
20
iex(8)> point[:z]
nil
iex(9)> point.x
10
iex(10)> point.y
20
iex(11)> point.z
** (KeyError) key :z not found in: %{x: 10, y: 20}
    iex:11: (file)
iex(11)> 

必須の値の場合はpoint.zの形式で使用しましょう。
キーが存在しない場合エラーになります。
pointが3次元の座標を表す場合、point.zが適切ですね。
これをpoint[:z]とすると、この部分ではエラーにならず、実際にこの値を使う段階でnilの為にエラーとなります。
エラーは隠さず早い段階で出すようにしたほうが良いです。

point[xx]の記述は、必須ではない値を取得する場合に便利です。

元ネタ
https://hexdocs.pm/elixir/1.16.0-rc.0/code-anti-patterns.html#non-assertive-map-access

11
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
0