gpt4 book ai didi

struct - 强制执行结构中的所有键

转载 作者:行者123 更新时间:2023-12-04 05:06:10 25 4
gpt4 key购买 nike

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

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_keysdefstruct自从 @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)

关于struct - 强制执行结构中的所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41609368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com