Learn X By Example · Elixir 篇 · If Else in Elixir
Elixir 中的if
和else
分支非常简单。
defmodule IfElseExample do
def run do
# Here's a basic example.
if rem(7, 2) == 0 do
IO.puts("7 is even")
else
IO.puts("7 is odd")
end
# You can have an `if` statement without an else.
if rem(8, 4) == 0 do
IO.puts("8 is divisible by 4")
end
# Logical operators like `and` and `or` are often useful in conditions.
if rem(8, 2) == 0 or rem(7, 2) == 0 do
IO.puts("either 8 or 7 are even")
end
# A variable can be assigned within the condition;
# it will be available in all branches.
num = 9
cond do
num < 0 -> IO.puts("#{num} is negative")
num < 10 -> IO.puts("#{num} has 1 digit")
true -> IO.puts("#{num} has multiple digits")
end
end
end
IfElseExample.run()
注意在 Elixir 中,条件不需要用小括号包裹,但是 do
和 end
关键字需要用来定义一个块。
运行上面的程序:
$ elixir if_else_example.exs
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Elixir 不像 Go 可以在条件中定义变量。而是在条件结构之前绑定变量。
同样,Elixir 也没有 else if
结构。对于多个条件,通常使用 cond
,如最后一个例子所示。或者也可以使用嵌套 if
语句,或者使用 case
和模式匹配。
Elixir 的 if
宏还有一个简短形式,类似于三元操作符:
result = if condition, do: value1, else: value2
这对于简单的条件赋值很有用。