Is it possible to have a function for setting values inside an existing struct? I'm talking about the idea of passing the existing struct into a function and setting that structs "name" value (for example)?
What I have:
main.exs
Code.require_file("user.exs") # Requiring in module
person1 = User.constructor("Name") # Making a new user
IO.write inspect person1
user.exs
defmodule User do
defstruct [name: ""]
def constructor(name) do
%User{name: name}
end
end
Any way to get this idea working?
def setName(struct, newName) do
struct.name = newName
end
Thanks
In Elixir, structs can only ever have the keys that you assigned to it in the defstruct macro. You can use %{struct | key => value} just fine as long as the value of key is one of the keys that struct has.
To define a struct, the defstruct construct is used: iex> defmodule User do ...> defstruct name: "John", age: 27 ...> end. The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they're defined in.
__MODULE__ is a compilation environment macros which is the current module name as an atom. Now you know alias __MODULE__ just defines an alias for our Elixir module. This is very useful when used with defstruct which we will talk about next.
Absolutely. There are several ways this can be accomplished.
defmodule User do
defstruct name: nil
# Method 1
def set_name(user, name) do
%{user | name: name}
end
# Method 2
def set_name(user, name) do
user |> struct(%{name: name})
end
# Method 3
def set_name(user, name) do
user |> Map.put(:name, name)
end
end
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