Search⌘ K
AI Features

use and __using__

Explore how to link Elixir modules using the use macro and __using__ function. Understand how these features enable powerful code injection and custom behaviors by implementing tracing in example modules. Gain practical knowledge about module extension and macro overriding for more effective Elixir programming.

Introduction

In one sense, use is a trivial function. We pass it a module along with an optional argument, and it invokes the function or macro __using__ in that module, passing it the argument.

Yet this simple interface gives us a powerful extension facility. For example, in our unit tests, we write use ExUnit.Case, and we get the test macro and assertion support. When we write an OTP server, we write use GenServer, and we get both a behaviour that documents the gen_server callback and default implementations of those callbacks.

Typically, the __using__ callback will be implemented as a macro, because it’ll be used to invoke code in the original module. ...