條件
cond do
0 == 1 -> IO.puts "0 = 1"
2 == 1 + 1 -> IO.puts "1 + 1 = 2"
3 == 1 + 2 -> IO.puts "1 + 2 = 3"
end
# Outputs "1 + 1 = 2" (first condition evaluating to true)
如果沒有條件,cond
將提升一個 CondClauseError
。
cond do
1 == 2 -> "Hmmm"
"foo" == "bar" -> "What?"
end
# Error
通過新增始終為真的條件可以避免這種情況。
cond do
... other conditions
true -> "Default value"
end
除非預計永遠不會達到預設情況,並且程式實際上應該在那時崩潰。