How to concat atoms in elixir?

I am looking for the best way of concatenating atoms, I have the following method:

String.to_atom("foo" <> Atom.to_string(:bar))
# :foobar
1 Like

It is not recommended to use String.to_atom because atoms are not garbage collected

One short way…

iex> :"foo#{:bar}"
:foobar
4 Likes

thanks but can you explain what you mean by that?

1 Like

It means if You reach the atom’s limit, your application will stop working

3 Likes

There’s a limit to the number of atoms that an application can have - it’s not good to dynamically create them.
Here’s a relevant thread: Is this a correct way to avoid wasting or reaching the atom limit? - #16 by rvirding

1 Like

This has the exact same problem as the code in the OP.

Therefore I’d advise against doing that as well!

The suggestion is to not generate atoms at runtime at all.

3 Likes

Yes it is the same problem… it was not meant to solve the problem of dynamic atom generation, just a shorter way to write bad code :slight_smile:

1 Like

it is actually present in the source code for ecto:
lib/ecto/schema.ex

opts = Keyword.put_new(opts, :foreign_key, :"#{name}_id")

That specific code is called at compile time, not runtime though.

2 Likes