Can the default value variables of a struct be defined as a function instead of raw value?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With