Go else if 語句
else if 語句
使用 else if
語句指定一個新條件,如果第一個條件為 false
。
語法
if condition1 {
// 如果 condition1 為真,則執行程式碼
} else if condition2 {
// 如果 condition1 為假,並且 condition2 為真,則執行程式碼
} else {
// 如果 condition1 和 condition2 都為假,則執行程式碼
}
使用 else if 語句
示例
此示例演示瞭如何使用 else if
語句。
package main
import ("fmt")
func main() {
time := 22
if time < 10 {
fmt.Println("Good morning.")
} else if time < 20 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
結果
Good evening.
示例說明
在上面的示例中,time (22) 大於 10,因此 **第一個條件** 為 false
。 else if
語句中的下一個條件也為 false
,因此我們將繼續執行 **else** 條件,因為 **condition1** 和 **condition2** 都為 false
- 並將 "Good evening" 列印到螢幕上。
但是,如果時間是 14,我們的程式將列印 "Good day."
示例
另一個使用 else if
的示例。
package main
import ("fmt")
func main() {
a := 14
b := 14
if a < b {
fmt.Println("a is less than b.")
} else if a > b {
fmt.Println("a is more than b.")
} else {
fmt.Println("a and b are equal.")
}
}
結果
a and b are equal.
示例
注意:如果 condition1 和 condition2 都為 true,則只有 condition1 的程式碼會被執行
package main
import ("fmt")
func main() {
x := 30
if x >= 10 {
fmt.Println("x is larger than or equal to 10.")
} else if x > 20 {
fmt.Println("x is larger than 20.")
} else {
fmt.Println("x is less than 10.")
}
}
結果
x is larger than or equal to 10.