defstruct構文を使います。
defstructには、アトムのリスト(デフォルト値をnilにする場合)か、キーワードリスト(デフォルト値を指定する場合)を渡します。
defmodule Plane do
defstruct [:engine, wings: 2]
end
plane = %Plane{}
# => %Plane{engine: nil, wings: 2}
マップを扱うほとんどの関数は、構造体でもそのまま使えます。
構造体のフィールドにアクセスするには、_静的アクセス演算子_の.を使うのがおすすめです。
フィールドの値の取得:
plane = %Plane{}
plane.engine
# => nil
Map.fetch(plane, :wings)
# => {:ok, 2}
フィールドの値の更新
plane = %Plane{}
%{plane | wings: 4}
# => %Plane{engine: nil, wings: 4}
@enforce_keysモジュール属性を使うと、構造体を作るときに、指定したフィールドを**nil以外**の値で初期化しなければならないという実行時チェックが行われます。@enforce_keysの後には、フィールドのキー(アトムです)のリストを書きます。defmodule User do
@enforce_keys [:username]
defstruct [:username]
end
%User{}
# => (ArgumentError) the following keys must also be given when building struct User: [:username]