Modules
Understand nested modules and different kinds of directives in Elixir.
We'll cover the following...
Modules provide namespaces for things we define. They also act as wrappers for macros, structs, protocols, and other modules. If we want to reference a function defined in a module from outside that module, we need to prefix the reference with the module’s name. We don’t need that prefix if code references something inside the same module as itself, as in the below example.
Run the Mod.func1
or Mod.func2
commands in the terminal below. Don’t forget to start an iex
session first with the iex -S mix
command.
defmodule First.MixProject do use Mix.Project def project do [ app: :first, version: "0.1.0", elixir: "~> 1.12", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} ] end def hello do [ IO.puts("Hello") ] end end
The func2
function can call func1
directly because it’s inside the same module (line 5). Outside the module, we have to use the fully qualified name—for example, Mod.func1
and Mod.func2
at lines 10 and 11, ...