Learn X By Example · Elixir 篇 · Switch in Elixir
下面是一个基本的 switch
。
defmodule SwitchExample do
def main do
i = 2
IO.write("Write #{i} as ")
case i do
1 -> IO.puts("one")
2 -> IO.puts("two")
3 -> IO.puts("three")
end
case :calendar.day_of_the_week(:calendar.local_time()) do
7 -> IO.puts("It's the weekend")
1 -> IO.puts("It's the weekend")
_ -> IO.puts("It's a weekday")
end
case :calendar.local_time() |> elem(0) |> elem(2) do
h when h < 12 -> IO.puts("It's before noon")
_ -> IO.puts("It's after noon")
end
what_am_i(true)
what_am_i(1)
what_am_i("hey")
end
defp what_am_i(i) do
case i do
_ when is_boolean(i) -> IO.puts("I'm a bool")
_ when is_integer(i) -> IO.puts("I'm an int")
_ -> IO.puts("Don't know type #{inspect(i)}")
end
end
end
SwitchExample.main()
将代码保存到 switch_example.exs
并使用 elixir
命令运行。
$ elixir switch_example.exs
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type "hey"
Elixir 是没有 switch 关键字的,case
里面用的是模式匹配,可以带有 guard,_
是万能匹配,相当于 default
。
case
会从上到下依次匹配,一旦匹配成功,分支后的表达式就是整个 case
语句的值,匹配也不会再继续。这和 Go 的switch
有点像,会自动 break。如果没有分支匹配成功,则会抛出异常。