This is not possible because attributes exist only until this particular module is compiled. When the module is compiled, all attributes are embedded and forgotten, so at the point where you can call functions from this module, changing the attributes is no longer possible.
This code should show this more clearly:
defmodule Test do @attr 1 @attr 2 def attr do @attr end end IO.inspect Test.attr
Please note that you can change the value of the attribute until the module has been compiled (for example, in the module) by simply setting it again, as I here, when setting @attr to 2 .
By the way, what you are trying to achieve can be easily done with Agent :
defmodule Storage do def start_link do Agent.start_link(fn -> 10 end, name: __MODULE__) end def add_to(input) do Agent.get_and_update(__MODULE__, fn (x) -> {x + input, x + input} end) end end Storage.start_link IO.inspect Storage.add_to(5)
A good rule of thumb in Elixir is that whenever you need to track some kind of volatile state, you will need to process the process that will consist.
PaweΕ obrok
source share