17

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?

Charlie
  • 4,197
  • 5
  • 42
  • 59
  • 2
    For what it's worth @SasaJuric did an excellent series of blog posts about macros and he covers the use statement in depth here: http://www.theerlangelist.com/2014/06/understanding-elixir-macros-part-2.html – Onorio Catenacci Mar 17 '15 at 17:02
  • 1
    Why is there an Erlang tag on this? – zxq9 Apr 13 '15 at 13:41
  • 1
    Figured there might be a decent number of people with an interest in both languages.. Also couldn't be sure if there was an equivalent feature in Erlang itself, or it's virtual machine. – Charlie Apr 13 '15 at 18:18
  • elixir poor document. I can not find answers after search ten minutes in google and `getting-started`. – Jiang YD Dec 10 '19 at 10:16

1 Answers1

31

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
Kanmaniselvan
  • 522
  • 1
  • 8
  • 23
Paweł Obrok
  • 22,568
  • 8
  • 74
  • 70
  • Cheers for the answer. A follow up question... When you use Mix to set up a new OTP app, do I have to 'require/use/import' the modules that I create in the /lib folder? because after I compile, it looks like I can (for example) call A.B.method from A.C without an explicit import directive. – Charlie Mar 17 '15 at 12:45
  • 3
    `require` has nothing to do with functions, it just makes the macros from the `require`’d module available to the current lexical scope. http://elixir-lang.org/getting-started/alias-require-and-import.html – Patrick Oscity Mar 17 '15 at 12:50
  • 1
    As long as your files are compiled you can call any function by specifying `Module.function_name` fully. If you use import you can use `function_name` omitting the `Module` which might be cleaner for cases where you use functions from a certain module a lot in some file for example. – Paweł Obrok Mar 17 '15 at 20:13
  • @obrok - Awesome reply (to the question in the comment). Exactly what I was aiming to confirm. – Charlie Mar 18 '15 at 21:32