Elixir中的If Else


Learn X By Example · Elixir 篇 · If Else in Elixir


Elixir 中的ifelse分支非常简单。

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 中,条件不需要用小括号包裹,但是 doend 关键字需要用来定义一个块。

运行上面的程序:

$ 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

这对于简单的条件赋值很有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值