1
use
和@before_compile
有什麼區別?兩者都可以用於向當前模塊注入一些代碼。`use`和`@ before_compile`有什麼區別?
use
和@before_compile
有什麼區別?兩者都可以用於向當前模塊注入一些代碼。`use`和`@ before_compile`有什麼區別?
一個主要區別是,在__using__
的代碼被稱爲和返回值,只要你叫use
模塊中注入,而被調用,並執行後,所有的代碼直接在模塊內注入的返回值,只在模塊編譯之前。
一個簡單的程序來演示的區別:
defmodule When do
defmacro __using__(_) do
IO.inspect :using
__CALLER__.module |> Module.definitions_in |> IO.inspect
quote do end
end
defmacro __before_compile__(_) do
IO.inspect :before_compile
__CALLER__.module |> Module.definitions_in |> IO.inspect
quote do end
end
end
defmodule Main do
@before_compile When
use When
IO.puts "added `@before_compile` and `use`"
def add(x, y), do: x + y
end
輸出:
:using
[]
added `@before_compile` and `use`
:before_compile
[add: 2]
ExUnit uses @before_compile
定義返回所有的測試,以使其能夠爲ExUnit亞軍獲得的功能和運行所有測試。