Lyn*_*ite 30 elixir switch-statement
在Elixir编程语言中,有两个类似的结构cond和case.两者都类似于其他语言switch或select其他语言
双方cond并case在描述此页
Gue*_*des 53
让我也if去俱乐部吧.你使用if一个条件和一个可能else,就是这样.如果cond有多个条件并且if语句不够,case则使用该语句,最后,当您想要模式匹配某些数据时使用该语句.
让我们通过例子解释一下:如果今天下雨或大米,你想要吃苹果,如果没有,你可以使用:
if weather == :raining do
IO.puts "I'm eating apple"
else
IO.puts "I'm eating rice"
end
Run Code Online (Sandbox Code Playgroud)
这是一个有限的世界,所以你想扩大你的选择,因此你会在某些条件下吃不同的东西,所以cond声明是这样的,像这样:
cond do
weather == :raining and not is_weekend ->
IO.puts "I'm eating apple"
weather == :raining and is_weekend ->
IO.puts "I'm will eat 2 apples!"
weather == :sunny ->
IO.puts "I'm happy!"
weather != :raining and is_sunday ->
IO.puts "I'm eating rice"
true ->
IO.puts "I don't know what I'll eat"
end
Run Code Online (Sandbox Code Playgroud)
最后true应该在那里,否则它会引发异常.
那么case呢?它用于模式匹配的东西.假设您收到有关天气和星期几的信息作为元组中的消息,您依靠它来做出决定,您可以将您的意图写成:
case { weather, weekday } do
{ :raining, :weekend } ->
IO.puts "I'm will eat 2 apples!"
{ :raining, _ } ->
IO.puts "I'm eating apple"
{ :sunny, _ } ->
IO.puts "I'm happy!"
{ _, :sunday } ->
IO.puts "I'm eating rice"
{ _, _ } ->
IO.puts "I don't know what I'll eat"
end
Run Code Online (Sandbox Code Playgroud)
因此,case带给您数据的模式匹配方法,您没有if或cond.
| 归档时间: |
|
| 查看次数: |
5344 次 |
| 最近记录: |