Programing

엘릭서 : 사용 vs 가져 오기

lottogame 2020. 7. 11. 10:02
반응형

엘릭서 : 사용 vs 가져 오기


차이 무엇 useimport?

주어진 컨텍스트를 현재 컨텍스트에 사용하기위한 간단한 메커니즘

https://hexdocs.pm/elixir/Kernel.SpecialForms.html#import/2

다른 모듈에서 함수 및 매크로를 가져옵니다.

한 가지 차이점은 import특정 기능 / 매크로를 선택하고 use모든 것을 가져 오는 것입니다.

다른 차이점이 있습니까? 언제 다른 것을 사용 하시겠습니까?


import ModuleModule네임 스페이스 없는 모든 함수와 매크로를 모듈에 가져옵니다 .

require Module매크로를 사용할 수는 Module있지만 가져 오지는 않습니다. (함수 Module는 항상 네임 스페이스로 제공됩니다.)

use Module첫 번째 requires모듈 다음에 __using__매크로 를 호출합니다 Module.

다음을 고려하세요:

defmodule ModA do
  defmacro __using__(_opts) do
    IO.puts "You are USING ModA"
  end

  def moda() do
    IO.puts "Inside ModA"
  end
end

defmodule ModB do
  use ModA

  def modb() do
    IO.puts "Inside ModB"
    moda()     # <- ModA was not imported, this function doesn't exist
  end
end

ModA.moda()가져 오지 않은 상태 에서는 컴파일 되지 않습니다 ModB.

그래도 다음은 컴파일됩니다.

defmodule ModA do
  defmacro __using__(_opts) do
    IO.puts "You are USING ModA"
    quote do          # <--
      import ModA     # <--
    end               # <--
  end

  def moda() do
    IO.puts "Inside ModA"
  end
end

defmodule ModB do
  use ModA

  def modb() do
    IO.puts "Inside ModB"
    moda()            # <-- all good now
  end
end

당신이 used와 같이 삽입 ModAimport문장을 생성 했다 ModB.


use는 현재 모듈에 코드를 주입하기위한 것이며 import함수를 가져 오는 데 사용됩니다. use예를 들어 use Timex모듈에 추가 때 Timex와 마찬가지로 함수를 자동으로 가져 오는 구현을 구축 할 수 있습니다. 내가 무엇을 의미하는지 알고 싶다면 timex.ex를 살펴보십시오 . use'd 일 수있는 모듈


보기 «, 별칭을 요구하고, 수입» 불로 불사의 영약 관계자로부터 페이지 시작 안내서 :

# Ensure the module is compiled and available (usually for macros)
require Foo

# Import functions from Foo so they can be called without the `Foo.` prefix
import Foo

# Invokes the custom code defined in Foo as an extension point
use Foo

필요

Elixir provides macros as a mechanism for meta-programming (writing code that generates code).

Macros are chunks of code that are executed and expanded at compilation time. This means, in order to use a macro, we need to guarantee its module and implementation are available during compilation. This is done with the require directive.

In general a module does not need to be required before usage, except if we want to use the macros available in that module.

Import

We use import whenever we want to easily access functions or macros from other modules without using the fully-qualified name. For instance, if we want to use the duplicate/2 function from the List module several times, we can import it:

iex> import List, only: [duplicate: 2]
List
iex> duplicate :ok, 3
[:ok, :ok, :ok]

In this case, we are importing only the function duplicate (with arity 2) from List.

Note that importing a module automatically requires it.

Use

Although not a directive, use is a macro tightly related to require that allows you to use a module in the current context. The use macro is frequently used by developers to bring external functionality into the current lexical scope, often modules.

Behind the scenes, use requires the given module and then calls the __using__/1 callback on it allowing the module to inject some code into the current context. Generally speaking, the following module:

defmodule Example do
  use Feature, option: :value
end

is compiled into

defmodule Example do
  require Feature
  Feature.__using__(option: :value)
end

With background from Python/Java/Golang languages, the import vs use was also confused for me. This will explain code reuse mechanism with some declarative languages examples.

import

In short, in Elixir, you don't need to import modules. All public functions can be accessed by full-qualified MODULE.FUNCTION syntax:

iex()> Integer.mod(5, 2)
1

iex()> String.trim(" Hello Elixir  ")
"Hello Elixir"

In Python/Java/Golang, you need to import MODULE before you can use functions in that MODULE, e.g Python

In []: import math

In []: math.sqrt(100)
Out[]: 10.0

Then what import in Elixir does might surprise you:

We use import whenever we want to easily access functions or macros from other modules without using the fully-qualified name

https://elixir-lang.org/getting-started/alias-require-and-import.html#import

So if you want to type sqrt instead of Integer.sqrt, trim instead of String.trim, import will help

iex()> import Integer
Integer
iex()> sqrt(100)
10.0

iex()> import String
String
iex()> trim(" Hello Elixir    ")
"Hello Elixir"

This might cause problems for reading code and when there is name-conflicting so it is not recommended in Erlang (the language that influences Elixir). But there is no such convention in Elixir, you can use it at own-risk.

In Python, the same effect can be done by:

from math import * 

and it only recommended to use in some special scenarios / interactive mode - for shorter/faster typing.

use & require

What makes use/require different is that they relate to "macro" - the concept that does not exist in Python/Java/Golang... family.

You don't need to import a module to use its functions, but you need to require a module to use its macros:

iex()> Integer.mod(5, 3) # mod is a function
2

iex()> Integer.is_even(42)
** (CompileError) iex:3: you must require Integer before invoking the macro Integer.is_even/1
    (elixir) src/elixir_dispatch.erl:97: :elixir_dispatch.dispatch_require/6
iex()> require Integer
Integer
iex()> Integer.is_even(42) # is_even is a macro
true

Though is_even can be written as a normal function, it is a macro because:

In Elixir, Integer.is_odd/1 is defined as a macro so that it can be used as a guard.

https://elixir-lang.org/getting-started/alias-require-and-import.html#require

use, to excerpt from Elixir doc:

use requires the given module and then calls the __using__/1 callback on it allowing the module to inject some code into the current context.

defmodule Example do
  use Feature, option: :value
end

is compiled into

defmodule Example do
  require Feature
  Feature.__using__(option: :value)
end

https://elixir-lang.org/getting-started/alias-require-and-import.html#use

So writing use X is same as writing

require X
X.__using__()

use/2 is a macro, macro will transform code into other code for you.

You will want to use MODULE when you:

  • want to access its macros (require)
  • AND execute MODULE.__using__()

Tested on Elixir 1.5


use Module requires Module and also calls __using__ on it.

import Module brings Module functionality into current context, not just requires it.

참고URL : https://stackoverflow.com/questions/28491306/elixir-use-vs-import

반응형