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

How to check type of struct's field in Elixir?

假设我有:

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

Elixir 中的类型规范是注释,如果不重复其中的一部分,您就无法真正地从代码中与它们交互。因此,你可以这样写:

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