无论您正在寻找终身保护/类型保证,是不可能的。结构是下面是裸露的地图 https://elixir-lang.org/getting-started/structs.html#structs-are-bare-maps-underneath:
defmodule Location do
@enforce_keys [:lat, :lon]
defstruct lat: 0, lon: 0
end
loc = %Location{lat: 0, lon: 0}
is_map(loc) #⇒ true
更重要的是,人们可以简单地创建一个map
with __struct__
键设置为原子,表示结构名称,瞧:
loc_str = %{__struct__: Location, lat: 0, lon: 0}
#⇒ %Location{lat: 0, lon: 0}
or use Kernel.struct/2 https://hexdocs.pm/elixir/Kernel.html#struct/2, that 不检查任何东西 https://github.com/elixir-lang/elixir/blob/1451797b919c03557f8c9c0468edd5a40c852600/lib/elixir/lib/kernel.ex#L1976:
struct(Location, [lat: 0, lon: 0])
#⇒ %Location{lat: 0, lon: 0}
也就是说,人们不应该对待struct
作为 Elixir 类型层次结构中的一等公民。这是一张带有附加字段的地图__struct__
set.
在 Elixir 中我们常用类型规格 https://elixir-lang.org/getting-started/typespecs-and-behaviours.html and dialyzer http://erlang.org/doc/man/dialyzer.html为此目的进行静态代码分析。