Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 为什么我需要'require'一个已经编译和加载的模块?_Elixir - Fatal编程技术网

Elixir 为什么我需要'require'一个已经编译和加载的模块?

Elixir 为什么我需要'require'一个已经编译和加载的模块?,elixir,Elixir,根据iex中的h require,require“需要编译和加载给定的模块”,“如果您想使用模块中的宏”,则需要 然而,似乎即使模块被编译和加载,我仍然需要调用require来调用它的宏。例如: # "require" the file in the sense of "go compile it right now" # Without doing this (or something equivilent, like `elixir -r macro_module.ex`), # a cal

根据
iex
中的
h require
require
“需要编译和加载给定的模块”,“如果您想使用模块中的宏”,则需要

然而,似乎即使模块被编译和加载,我仍然需要调用
require
来调用它的宏。例如:

# "require" the file in the sense of "go compile it right now"
# Without doing this (or something equivilent, like `elixir -r macro_module.ex`),
# a call to `require MacroModule` will fail with CompileError: "module MacroModule
# is not loaded and could not be found"
Code.require_file("path/to/macro_module.ex")

defmodule MyModule1 do
  require MacroModule
  MacroModule.some_macro # works
end

defmodule MyModule2 do
  # fails with CompileError: "you must require MacroModule before invoking the
  # macro MacroModule.some_macro/0"
  MacroModule.some_macro
end
当宏模块在
MyModule1
中成功使用时,我为什么需要
MyModule2
中要求宏模块

(我看到文档中说,
require
是词汇范围,但我不太明白在这种情况下,因为我使用的是像
MacroModule这样的全局引用。一些宏
,而不是像
import MacroModule这样的本地宏;一些宏

解释了require的范围规则。基本上,require语句只在调用它的do块的范围内有效。因此它应该是这样的:

defmodule MyModule1 do
  require MacroModule #require now in scope
  MacroModule.some_macro 
end #require goes out of scope

我正在使用Elixir 1.2.1,我也不理解“未加载且无法找到”消息。在它说“找不到”之前,它在哪里找过
require
不像Ruby那样在加载路径中搜索文件。让我困惑的是,
宏模块。一些看起来不像本地引用的_macro
,仍然只在调用了
require MyMacro
的作用域中可用。但我想,事情就是这样可能与宏观卫生有关,但这只是我的猜测。我的意思是,它可能与防止宏溢出到其他模块中有关。