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.operator
是logic
,arithmetic
还是nil
?
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)
归档时间: |
|
查看次数: |
1377 次 |
最近记录: |