【问题标题】:Why IO.puts prints to terminal in a module if is not called如果未调用 IO.puts 为什么会在模块中打印到终端
【发布时间】:2015-09-03 18:47:23
【问题描述】:

我有一个问题,我有这个模块

defmodule Example do

  IO.puts "Creating a function"

  def sum(a, b) do
      a + b
  end

  IO.puts "End of the function”
end

当我用 elixirc example.ex 编译它时,我得到了这个

Creating a function
End of the function

为什么?我只是编译文件,我没有从任何地方调用这个模块

【问题讨论】:

  • 我会说你错了,它也在运行它。 :-)
  • 你确定你做的是“elixir”而不是“elixir”?
  • 是的,我敢肯定,其实我做过elixir和elixirc

标签: elixir


【解决方案1】:

在 Elixir 中定义一个模块 执行该模块内的代码。事实上,甚至“def”本身也只是一个宏,它获取函数内容并将它们存储在某个地方。一切都是一种表达。这就是为什么您可以执行条件定义,例如:

defmodule Example do
  if true do
    def sum(a, b) do
      a + b
    end
  end
end

这就是代码按照您看到的方式运行的原因。

PS:elixir 和 elixirc 将显示相同的行为,因为它们之间的唯一区别是一个将 .beam 文件写入磁盘,另一个不写入。

【讨论】:

  • 谢谢,我有这个想法,但我不确定。现在我确定一切都是表达式并返回一个值。
猜你喜欢
  • 2021-01-20
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多