Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Modules & Structs

modules_and_structs.livemd

Modules & Structs

Section

DateTime.utc_now()
defmodule Now do
  @date_time DateTime.utc_now()

  def my_date do
    DateTime.utc_now()
  end
end
Now.my_date()

Modules vs Functions

defmodule Greeting do
  def hello do
    # Only used within the function it's defined in
    pretty_print = fn value ->
      IO.puts("=========")
      IO.inspect(value)
      IO.puts("=========")
    end

    pretty_print("Hello")
  end

  def hi do
    pretty_print("Hi")
  end

  # publicly available
  # use this anywhere in the codebase
  def pretty_print(value) do
    IO.puts("=========")
    IO.inspect(value)
    IO.puts("=========")
  end

  # anywhere within the module
  defp pretty_print(value) do
    IO.puts("=========")
    IO.inspect(value)
    IO.puts("=========")
  end
end

Greeting.hi()

Structs

defmodule Person do
  defstruct [:name, :favourite_books, :school]
end
defmodule School do
  defstruct [:city, :name]
end
jon = %Person{
  name: "Jon",
  favourite_books: ["Tao Te Ching"],
  school: %School{city: "Guadalajara", name: "Colegio Salesiano"}
}
%{jon | favourite_books: jon.favourite_books ++ ["A confederacy of dunces"]}
struct = %Person{name: "Jon", age: 20003}
struct = %Person{name: "Jon"}
%{struct | name: "Bill"}
defmodule Name do
  @enforce_keys [name: "person"]
  defstruct @enforce_keys
end
%Name{name: nil}