defstruct elixir code example
Example 1: elixir struct
defmodule UserModule do
# UserModule struct definition
# Put this inside a module definition
defstruct [:first_name, :last_name, :age]
# functions to access the struct data,
# horever if the struct and functions life in the same module,
# you can replace the module name with __MODULE__ attributte.
# Ej %UserModule{} is the same that %__MODULE__{}
def first_name(%__MODULE__{first_name: name}),
do: name
def last_name(%__MODULE__{last_name: name}),
do: name
def age(%__MODULE__{age: age}),
do: age
end
# For usage this, you can do (in iex for example):
> user = %UserModule{first_name: "martin", last_name: "alganaraz", age: 40}
> UserModule.first_name user
"martin"
Example 2: elixir struct example
# struct example
%__MODULE__{
name: "apple",
location: {40,0,1},
}