如何在Elixir中检查struct的字段类型?

zie*_*ony 8 elixir typechecking

比方说我有:

defmodule Operator do

    defstruct operator: nil 

    @type t :: %Operator {
        operator: oper
    }

    @type oper :: logic | arithmetic | nil
    @type logic :: :or | :and
    @type arithmetic :: :add | :mul 

end
Run Code Online (Sandbox Code Playgroud)

然后我可以:

o = %Operator{operator: :and}
Run Code Online (Sandbox Code Playgroud)

它是可能的,以检查是否o.operatorlogic,arithmetic还是nil

Jos*_*lim 8

Elixir中的Typespecs是注释,你不能真正地从代码中与它们交互而不重复它们的一部分.因此,你可以写:

def operator(%Operator{operator: op}) when op in [:or, :and, :add, :mul, nil] do
  ...
end
Run Code Online (Sandbox Code Playgroud)

或者:

@ops [:or, :and, :add, :mul, nil]

def operator(%Operator{operator: op}) when op in @ops do
  ...
end
Run Code Online (Sandbox Code Playgroud)