gpt4 book ai didi

elixir - 如何导入在另一个文件中定义的自定义模块?

转载 作者:行者123 更新时间:2023-12-03 23:21:49 24 4
gpt4 key购买 nike

a.exs:

defmodule A do
def greet, do: IO.puts "hello"
end

b.exs:
defmodule B do
import A
def say_hello, do: greet
end

结果:
~/elixir_programs$ iex b.exs
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

** (CompileError) b.exs:2: module A is not loaded and could not be found
~/elixir_programs$ tree .
.
├── a.exs
├── app1.exs
├── b.exs
....

就此而言,您如何使用限定名称来调用在另一个模块中定义的函数:

b.exs:
defmodule B do
def say_hello, do: A.greet
end
~/elixir_programs$ iex b.exs
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> B.say_hello
** (UndefinedFunctionError) function A.greet/0 is undefined (module A is not available)
A.greet()

好的,这有效:
iex(1)> c "a.exs"
[A]

iex(2)> B.say_hello
hello
:ok

最佳答案

关于 Elixir 有两点主要应该了解:它是一种编译语言,它区分编译文件和脚本(后者也被编译,但它们不会通过 mix 默认情况下自动编译。)

与脚本语言(ruby,python,javascript,...)不同,编译语言应该在功能可用之前通过两个阶段:应该编译文件,然后应该加载运行时(阅读:Erlang VM)。不能只是require 'foo'就像我们在 ruby​​ 中所做的那样或 import bar就像我们在 python 中所做的那样,并期望它能够正常工作。

Elixir 提供了方便的助手来在 Code 中进行运行时编译。模块,包括但不限于: Code.require_file/2 Code.compile_file/2 .

使用 mix 时, 只有非脚本文件,扩展名为 .ex , 默认编译。这就是为什么作为脚本的测试文件( .exs )永远不会与运行时发生冲突。

也就是说,有四个主要选项可以使其工作:

  • 使用mix名为 a.ex 的项目和文件和 b.ex .这样你就可以通过运行 iex -S mix 得到所有手头的东西,编译。 .
  • 使用Code.require_file("a.exs")来自您的b.exs明确要求 a.exs .
  • 告诉 iex通过运行 iex -r a.exs -r b.exs 编译(如果需要)并加载所有文件.
  • 像在答案中那样手动进行编译。
  • 关于elixir - 如何导入在另一个文件中定义的自定义模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663420/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com