Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to generate atoms dynamically in Elixir?

Tags:

erlang

elixir

Is there a way to declare atoms dynamically in Elixir?

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

like image 829
Shih-Min Lee Avatar asked Oct 05 '17 17:10

Shih-Min Lee


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)
like image 191
ryanwinchester Avatar answered Nov 15 '22 11:11

ryanwinchester