如何在不需要复制所有键的情况下强制执行结构中的所有键?为了澄清,我想干这个:
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
它工作正常,但看起来很吵.有没有更好的方法?
你可以传递@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)