Use all keys in the structure

How can I enforce all keys in a structure without having to duplicate all keys? To clarify, I would like to do this:

defmodule Ticket do @enforce_keys [:origin, :destination, :price] defstruct [:origin, :destination, :price] end 

I can use an additional variable:

 defmodule Ticket do struct_keys = [:origin, :destination, :price] @enforce_keys struct_keys defstruct struct_keys end 

It works correctly, but it looks noisy. Is there a better approach?

+5
source share
1 answer

You can pass @enforce_keys to defstruct , since @enforce_keys is just a normal module attribute:

 defmodule Ticket do @enforce_keys [:origin, :destination, :price] defstruct @enforce_keys end 
 iex(1)> defmodule Ticket do ...(1)> @enforce_keys [:origin, :destination, :price] ...(1)> defstruct @enforce_keys ...(1)> end iex(2)> %Ticket{} ** (ArgumentError) the following keys must also be given when building struct Ticket: [:origin, :destination, :price] expanding struct: Ticket.__struct__/1 iex:2: (file) 
+11
source

Source: https://habr.com/ru/post/1262685/


All Articles