Reputation: 12112
Can the default value variables of a struct be defined as a function instead of raw value?
Upvotes: 4
Views: 3972
Reputation: 7469
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}
Upvotes: 9