官术网_书友最值得收藏!

  • Mastering Elixir
  • André Albuquerque Daniel Caixinha
  • 242字
  • 2021-08-05 10:42:44

Atoms

Atoms are a constant, whose value is its own name. They are always prefixed with a leading colon (:), followed by alphanumeric characters (and possibly _ or @). They may terminate with an exclamation or a question mark. Atoms are similar to enumerations in C and symbols in Ruby. Here are some examples of atoms:

iex> :ok
:ok
iex> :error
:error
iex> :some_descriptive_name!
:some_descriptive_name!
iex> :value@start
:value@start

You can create atoms with arbitrary characters with the following syntax:

iex> :"Atom name with arbitrary characters#$%^"
:"Atom name with arbitrary characters#$%^"

As with all data structures in Elixir, atoms can't be modified after their creation. Furthermore, they are not garbage-collected. Atoms are kept in the atom table, and upon compilation, their value is replaced by a reference to their entry on this table. This makes comparing atoms very efficient. As you'll learn throughout this book, this is one of the major use cases for atoms in Elixir, as we are constantly matching the return of a function against a certain expected atom.

Since atoms are not garbage collected, don't create atoms dynamically from sources you can't control, as you can very easily use up all of the space allocated for the atom table. For instance, if you're parsing a JSON response and creating a map out of it, don't use atoms for its keys—use strings instead (both of these types, maps and strings, will be described later in this chapter).
主站蜘蛛池模板: 罗江县| 海淀区| 宁强县| 左权县| 福鼎市| 容城县| 迭部县| 赣榆县| 天柱县| 上虞市| 甘泉县| 荣成市| 哈巴河县| 尼木县| 玉山县| 勐海县| 古浪县| 太和县| 渭南市| 西城区| 寻甸| 宝坻区| 建湖县| 庄河市| 赣榆县| 三江| 改则县| 岑巩县| 开封县| 许昌县| 南安市| 津南区| 邻水| 武鸣县| 宜宾县| 鄄城县| 弥渡县| 金湖县| 民乐县| 乌兰浩特市| 台北市|