强制执行结构中的所有键

时间:2017-01-12 09:26:38

标签: struct elixir

如何在不需要复制所有键的情况下强制执行结构中的所有键?为了澄清,我想干这个:

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

我可以使用其他变量:

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

它工作正常,但看起来很吵。有没有更好的方法?

1 个答案:

答案 0 :(得分:16)

您可以将@enforce_keys传递给defstruct,因为@enforce_keys只是一个正常的模块属性:

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)