Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting existing struct value in Elixir?

Tags:

elixir

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

like image 713
Molnár Márk Avatar asked Jan 27 '16 14:01

Molnár Márk


People also ask

How do you update a struct in Elixir?

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.

How do you declare a struct in Elixir?

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.

What is __ module __ In elixir?

__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.


1 Answers

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
like image 146
Christian Di Lorenzo Avatar answered Sep 30 '22 13:09

Christian Di Lorenzo