我想在typespec和guard中使用module属性 @magic_constant:
defmodule Example do
@magic_constant 1
@type t :: @magic_constant
def f(i) when i == 1 do
:ok
end
end
Run Code Online (Sandbox Code Playgroud)
当我使用Elixir v1.5尝试此操作时,会报告以下编译错误:
== Compilation error in file lib/example.ex ==
** (CompileError) lib/example.ex:4: type '@'(_) undefined
(stdlib) lists.erl:1338: :lists.foreach/2
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
[1] 17240 exit 1 mix compile
Run Code Online (Sandbox Code Playgroud)
有没有办法在守卫和typepecs中使用常量?
您可以使用unquote在typespec中注入module属性的值.
defmodule Example do
@magic_constant 1
@type t :: unquote(@magic_constant)
end
Run Code Online (Sandbox Code Playgroud)
iex(1)> t Example
@type t() :: 1
Run Code Online (Sandbox Code Playgroud)