Search code examples
erlangelixir

Is there a way to generate atoms dynamically in Elixir?


Is there a way to declare atoms dynamically in Elixir?

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


Solution

  • 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, and should normally be limited to atoms you know exist.

    However, to answer your question. Yes.

    Example:

    iex(1)> str = "aaa"
    "aaa"
    
    iex(2)> String.to_atom(str)
    :aaa
    
    iex(3)> :foo
    :foo
    
    # Use `String.to_existing_atom/1` if you can.
    
    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)