Is there a way to generate atoms dynamically in Elixir?

Viewed 978

Is there a way to declare atoms dynamically in Elixir?

like str = "aaa" and we want to create an atom called :aaa.

1 Answers

Yes, you can.

However, you need to be careful as atoms are not garbage collected and there are limits to the amount of atoms you can have (the default limit is 1,048,576). It might seem like a lot, but if your app runs for a long time and you are dynamically generating atoms, you will eventually hit the limit.

It is generally considered a bad idea to dynamically generate them.

However, to answer your question. Yes.

Example:

iex(1)> str = "aaa"
"aaa"

iex(2)> String.to_atom(str)
:aaa

iex(3)> :foo
:foo

iex(4)> String.to_existing_atom("foo")
:foo

iex(5)> String.to_existing_atom("bar")
** (ArgumentError) argument error
    :erlang.binary_to_existing_atom("bar", :utf8)
Related