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

8

假设我有以下内容:

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.operator逻辑运算符算术运算符还是nil

1个回答

9

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

谢谢。我会考虑一些宏来完成这个任务。 - zie1ony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接