Structs in Elixir

To encapsulate the given Go example into Elixir, the structure, syntax, and idiomatic expressions of Elixir will be employed while maintaining the original explanations where applicable.

Structs in Elixir are defined within modules, and functions encapsulating struct creation mimic constructor functions. Below is the translation:


Structs

Elixir’s defstruct are used to define structs by specifying the fields and their default values. They are used to group related data together to form records.

This Person struct type has name and age fields.

defmodule Person do
  defstruct name: "", age: 0
end

new_person/1 constructs a new person struct with the given name.

defmodule Person do
  defstruct name: "", age: 42

  def new_person(name) do
    %Person{name: name}
  end
end

Example usage in Elixir

This syntax creates a new struct.

IO.inspect(%Person{name: "Bob", age: 20})

You can name the fields when initializing a struct.

IO.inspect(%Person{name: "Alice", age: 30})

Omitted fields will be zero-valued.

IO.inspect(%Person{name: "Fred"})

The % prefix yields a struct in Elixir.

IO.inspect(%Person{name: "Ann", age: 40})

It’s idiomatic to encapsulate new struct creation in constructor functions.

IO.inspect(Person.new_person("Jon"))

Access struct fields with a ..

s = %Person{name: "Sean", age: 50}
IO.inspect(s.name)

You can also use dots with struct variables.

sp = s
IO.inspect(sp.age)

Structs are mutable by creating a new struct with updated values.

sp = %Person{sp | age: 51}
IO.inspect(sp.age)

If a struct type is only used for a single value, we don’t have to give it a name. The value can have an anonymous struct type simple by defining the map.

dog = %{
  name: "Rex",
  is_good: true
}

IO.inspect(dog)

Running Elixir Code

To execute the program and see the results, save the code in an .exs file, such as structs_example.exs, and run it using the Elixir interpreter.

$ elixir structs_example.exs
%Person{age: 20, name: "Bob"}
%Person{age: 30, name: "Alice"}
%Person{age: 42, name: "Fred"}
%Person{age: 40, name: "Ann"}
%Person{age: 42, name: "Jon"}
"Sean"
50
51
%{is_good: true, name: "Rex"}

Next example: Methods.