defmodule Example do
def greeting(name) do
"Hello #{name}."
end
end
iex> Example.greeting "Sean"
"Hello Sean."
Elixir 也允许嵌套的模块,这让你可以轻松定义多层命名空间:
defmodule Example.Greetings do
def morning(name) do
"Good morning #{name}."
end
def evening(name) do
"Good night #{name}."
end
end
iex> Example.Greetings.morning "Sean"
"Good morning Sean."
模块属性
模块的属性通常被用作常量,来看一下简单的例子:
defmodule Example do
@greeting "Hello"
def greeting(name) do
~s(#{@greeting} #{name}.)
end
end
defmodule Sayings.Greetings do
def basic(name), do: "Hi, #{name}"
end
defmodule Example do
alias Sayings.Greetings
def greeting(name), do: Greetings.basic(name)
end
# Without alias
defmodule Example do
def greeting(name), do: Sayings.Greetings.basic(name)
end
如果别名有冲突,或者我们想要给那个模块命一个不同的名字时,我们可以用 :as 参数:
defmodule Example do
alias Sayings.Greetings, as: Hi
def print_message(name), do: Hi.basic(name)
end
Elixir 也允许一次指定多个别名:
defmodule Example do
alias Sayings.{Greetings, Farewells}
end
import
我们可以用 import 从另一个模块中导入函数:
iex> last([1, 2, 3])
** (CompileError) iex:9: undefined function last/1
iex> import List
nil
iex> last([1, 2, 3])
3
defmodule Hello do
defmacro __using__(opts) do
greeting = Keyword.get(opts, :greeting, "Hi")
quote do
def hello(name), do: unquote(greeting) <> ", " <> name
end
end
end
然后我们在 Example 模块中使用新加的这个 greeting 参数:
defmodule Example do
use Hello, greeting: "Hola"
end
我们打开 IEx 来验证 greeting 的内容已经被改变了:
iex> Example.hello("Sean")
"Hola, Sean"
上面这些简单的例子展示了 use 的用法。use 是 Elixir 工具箱中非常强大的一个。在你学习 Elixir 的过程中,多留意一下, 你会看到很多使用 use 的地方,之前我们已经遇到过的一个例子就是 use ExUnit.Case, async: true。