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

  • 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).
主站蜘蛛池模板: 宽城| 晋州市| 德清县| 呼和浩特市| 武宣县| 东乡| 冕宁县| 汝州市| 汾阳市| 壤塘县| 安吉县| 灵山县| 文水县| 临澧县| 威宁| 盐亭县| 长子县| 临颍县| 大英县| 乐至县| 克拉玛依市| 隆安县| 长阳| 虎林市| 嘉祥县| 南安市| 龙南县| 偃师市| 巴东县| 连云港市| 兴国县| 太仓市| 莱西市| 肥东县| 策勒县| 揭阳市| 华宁县| 岢岚县| 河北省| 波密县| 英德市|