Elixir Modules and Structs — Organization and Data with Types
DodaTech
Updated 2026-06-29
1 min read
In this tutorial, you will learn about Elixir Modules and Structs. We cover key concepts, practical examples, and best practices to help you master this topic.
Modules in Elixir group functions together, while structs provide typed, named fields for data. Together they form the building blocks of well-organized Elixir applications.
In this tutorial, you'll learn how to structure Elixir code with modules and structs.
Modules
defmodule MyApp.Greeter do
@moduledoc "Handles greetings"
@default_name "World" # Module attribute (constant)
def hello(name \ @default_name) do
"Hello, #{name}!"
end
end
MyApp.Greeter.hello() # => "Hello, World!"
MyApp.Greeter.hello("Alice") # => "Hello, Alice!"
Structs
defmodule User do
defstruct [:name, :age, :email]
@type t :: %User{
name: String.t(),
age: non_neg_integer(),
email: String.t()
}
def create(name, age, email) do
%User{name: name, age: age, email: email}
end
def adult?(%User{age: age}), do: age >= 18
end
# Creating
alice = %User{name: "Alice", age: 30, email: "alice@example.com"}
alice.name # => "Alice"
# Pattern matching on structs
%User{name: name} = alice
name # => "Alice"
# Required fields
defmodule Config do
@enforce_keys [:host, :port]
defstruct [:host, :port, :protocol]
end
# %Config{port: 8080} # Error! Missing required key :host
%Config{host: "localhost", port: 8080} # OK
← Previous
Elixir Pipe Operator — Data Transformation Pipelines
Next →
Elixir OTP — GenServer, Supervisor, and Application
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro