Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: struct default value from function

Can the default value variables of a struct be defined as a function instead of raw value?

like image 993
tldr Avatar asked Jan 10 '23 14:01

tldr


1 Answers

A default value for a struct field is an expression evaluated at the time of struct definition.

Proof:

# struct.exs
defmodule M do
  defstruct [a: IO.gets("> ")]
end

# ...

$ iex struct.exs
Erlang/OTP 17 [erts-6.0] ...

> hello
Interactive Elixir (0.13.3-dev) - ...
iex(1)> %M{}
%M{a: "hello\n"}

You can define a function that will create a struct and will set some of its fields:

# struct.exs
defmodule M do
  defstruct [a: nil]

  def new(val) do
    %M{a: val}
  end
end

# ...

M.new(123)
#=> %M{a: 123}
like image 139
Alexei Sholik Avatar answered Jan 19 '23 16:01

Alexei Sholik