Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - What does the 'use' keyword do?

I suspect it's an elementary question, but it's been hard to find a succinct, canonical answer online.

From what little I understand;

  • It's distinct from both 'require' and 'import'
  • It's used to import the contents of modules.
  • It's a macro

Can anyone clarify?

like image 295
Charlie Avatar asked Mar 17 '15 11:03

Charlie


People also ask

What is keyword list in Elixir?

12.3) A keyword list is a list that consists exclusively of two-element tuples. The first element of these tuples is known as the key, and it must be an atom. The second element, known as the value, can be any term.

What is use elixir?

here's a lightweight explanation of 'use' in elixir as I currently understand it. Use is a tool to reuse code just like require, import, and alias. Use simply calls the __using__ macro defined in another module. The __using__ macro allows you to inject code into another module.

What is a macro elixir?

12.3) Macros are compile-time constructs that are invoked with Elixir's AST as input and a superset of Elixir's AST as output. Let's see a simple example that shows the difference between functions and macros: defmodule Example do defmacro macro_inspect(value) do IO.

What does elixir add to Erlang?

Adding Elixir to existing Erlang programs Elixir compiles into BEAM byte code (via Erlang Abstract Format). This means that Elixir code can be called from Erlang and vice versa, without the need to write any bindings. All Elixir modules start with the Elixir.


1 Answers

It requires the given module and then calls the __using__/1 callback on it allowing the module to inject some code into the current context. See https://elixir-lang.org/getting-started/alias-require-and-import.html#use.

Example:

defmodule Test do
  use Utility, argument: :value
end

is about the same as

defmodule Test do
  require Utility
  Utility.__using__(argument: :value)
end
like image 54
Paweł Obrok Avatar answered Oct 17 '22 21:10

Paweł Obrok