如何检查Elixir中struct结构的类型?

时间:2015-01-17 18:04:32

标签: 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

然后我可以:

o = %Operator{operator: :and}

是否可以检查o.operatorlogicarithmetic还是nil

1 个答案:

答案 0 :(得分:8)

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

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

或者:

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

def operator(%Operator{operator: op}) when op in @ops do
  ...
end