What is the Elixir module?

Overview

Modules are used to organize functions into a namespace, as well as define named and private functions.

Modules are not classes. In modules, we don’t have constructors and destructors.

Syntax

defmodule module_name do

   functions and other logic

end

Example

#Module
defmodule Example do
def greeting(name) do
IO.puts "Hello #{name}."
end
end
Example.greeting "Elijah"

Code explanation

In the code above, we see the following:

  • In line 2, we create a module Example.

  • In lines 3-5, we create a greeting function.

  • In line 4, we set the logic of the function to output the greeting.

  • In line 7, we call the Example.greeting "Elijah" that gives the greeting output.

Layering modules in Elixir allows us to namespace our functionality even more.

#Module
defmodule Example.Greetings do
def morning(name) do
IO.puts"Good morning #{name}."
end
#function definition
def evening(name) do
IO.puts"Good night #{name}."
end
end
Example.Greetings.evening"Elijah"

Code explanation

In the code above, we see the following:

  • In line 2, we layer two modules Example.Greetings.

  • In lines 3-5, we create a morning function to print the message “Good Morning”.

  • In lines 7-9, we create a evening function to print the message “Good Evening”.

  • In line 11, we call the Example.Greetings.evening "Elijah" that gives the greeting output.

Free Resources