Learn X By Example · Elixir 篇 · Constants in Elixir
以下程序展示了常量的使用。
defmodule Constants do
def print_constants do
# Declares a constant value
s = "constant"
IO.puts(s)
# A const statement can appear anywhere a var statement can
n = 500_000_000
# Constant expressions perform arithmetic with arbitrary precision
d = 3.0e20 / n
IO.puts(d)
# A numeric constant has no type until it’s given one, such as by an explicit conversion
IO.puts(trunc(d))
# A number can be given a type by using it in a context that requires one, such as a variable
# assignment or function call. For example, here math.sin expects a float
IO.puts(:math.sin(n))
end
end
Constants.print_constants()
将代码保存到扩展名为 .exs
的文件中,然后使用 Elixir 解释器运行。
$ elixir constants.exs
constant
6.0e+11
600000000000
-0.28470407323754404
这也太简单了,下一个,下一个。