原文:CalliCoder — Golang Control Flow Statements: If, Switch and For
if 陳述式
if
陳述式用於根據給定的條件,決定是否應執行程式碼區塊。
以下是 Golang 中 if
陳述式的語法:
if(condition) {
// Code to be executed if the condition is true.
}
這裡有個簡單的範例:
package main
import "fmt"
func main() {
var x = 25
if x%5 == 0 {
fmt.Printf("%d is a multiple of 5\n", x)
}
}
# Output
25 is a multiple of 5
注意,你可以在 Golang 中的 if
陳述式省略 ()
,但大括號 {}
是必需的:
var y = -1
if y < 0 {
fmt.Printf("%d is negative\n", y)
}
如下所示,你可以使用捷徑運算子 &&
和 ||
來組合多個條件:
var age = 21
if age >= 17 && age <= 30 {
fmt.Println("My Age is between 17 and 30")
}
if-Else 陳述式
if
陳述式可以與 else
區塊結合使用。如果 if
陳述式中指定的條件不成立,則執行 else
區塊。
if condition {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
這裡有個簡單的範例:
package main
import "fmt"
func main() {
var age = 18
if age >= 18 {
fmt.Println("You're eligible to vote!")
} else {
fmt.Println("You're not eligible to vote!")
}
}
# Output
You're eligible to vote!
if-else-if 鏈
if
陳述式也可以包含多個 else if
部分,從而構成一系列條件,例如:
package main
import "fmt"
func main() {
var BMI = 21.0
if BMI < 18.5 {
fmt.Println("You are underweight");
} else if BMI >= 18.5 && BMI < 25.0 {
fmt.Println("Your weight is normal");
} else if BMI >= 25.0 && BMI < 30.0 {
fmt.Println("You're overweight")
} else {
fmt.Println("You're obese")
}
}
# Output
Your weight is normal
if 搭配簡短宣告
Golang 中的 if
陳述式還可以在條件表達式之前包含一個簡短宣告:
if n := 10; n%2 == 0 {
fmt.Printf("%d is even\n", n)
}
在簡短宣告中宣告的變數僅可在 if
區塊及它的 else
或 else-if
分支內使用:
if n := 15; n%2 == 0 {
fmt.Printf("%d is even\n", n)
} else {
fmt.Printf("%d is odd\n", n)
}
注意,如果你使用簡短陳述式,則不能使用括號。因此,以下程式碼將產生語法錯誤:
// You can't use parentheses when `if` contains a short statement
if (n := 15; n%2 == 0) { // Syntax Error
}
switch 陳述式
Switch 陳述式採用表達式並將其與可能的條件清單匹配。找到匹配項目後,它會執行指定匹配條件區塊內的程式碼。
這裡有個簡單的 switch 陳述式範例:
package main
import "fmt"
func main() {
var dayOfWeek = 6
switch dayOfWeek {
case 1: fmt.Println("Monday")
case 2: fmt.Println("Tuesday")
case 3: fmt.Println("Wednesday")
case 4: fmt.Println("Thursday")
case 5: fmt.Println("Friday")
case 6: {
fmt.Println("Saturday")
fmt.Println("Weekend. Yaay!")
}
case 7: {
fmt.Println("Sunday")
fmt.Println("Weekend. Yaay!")
}
default: fmt.Println("Invalid day")
}
}
# Output
Saturday
Weekend. Yaay!
Go 會從上到下逐一評估所有 switch 條件,直到條件成功為止。它會執行該指定條件區塊內的程式碼,然後停止(不會再評估其他條件)。
與其他語言如 C、C++ 和 Java 相反的是,你需要明確地在每個條件區塊之後插入一個 break
陳述式,來停止對後續條件的評估。
如果所有條件都不成功,則執行預設條件。
switch 搭配簡短宣告
就像 if
一樣,switch
也可以在條件表達式之前包含一個簡短宣告。因此,你也可以像這樣撰寫先前的 switch 範例:
switch dayOfWeek := 6; dayOfWeek {
case 1: fmt.Println("Monday")
case 2: fmt.Println("Tuesday")
case 3: fmt.Println("Wednesday")
case 4: fmt.Println("Thursday")
case 5: fmt.Println("Friday")
case 6: {
fmt.Println("Saturday")
fmt.Println("Weekend. Yaay!")
}
case 7: {
fmt.Println("Sunday")
fmt.Println("Weekend. Yaay!")
}
default: fmt.Println("Invalid day")
}
唯一不同的是,簡短陳述式宣告的變數 dayOfWeek
僅可在 switch 區塊內使用。
合併多個 switch 條件
你可以像這樣將多個 switch
條件合併成一個:
package main
import "fmt"
func main() {
switch dayOfWeek := 5; dayOfWeek {
case 1, 2, 3, 4, 5:
fmt.Println("Weekday")
case 6, 7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid Day")
}
}
# Output
Weekday
當你需要針對多種情況執行共同的邏輯時,這非常方便。
不帶表達式的 switch
在 Golang 中,我們在 switch
陳述式中指定的表達式是非必要的。不帶表達式的 switch
與 switch true
相同。它逐一評估所有條件,並執行第一個條件成功的區塊:
package main
import "fmt"
func main() {
var BMI = 21.0
switch {
case BMI < 18.5:
fmt.Println("You're underweight")
case BMI >= 18.5 && BMI < 25.0:
fmt.Println("Your weight is normal")
case BMI >= 25.0 && BMI < 30.0:
fmt.Println("You're overweight")
default:
fmt.Println("You're obese")
}
}
不帶表達式的 switch 只是一個撰寫 if-else-if
鏈的簡潔方式。
for 迴圈
迴圈用於重複執行程式碼區塊。Golang 只有一個迴圈陳述式:for
迴圈。
以下是 Go 中 for
迴圈的一般語法:
for initialization; condition; increment {
// loop body
}
初始化陳述式只會在迴圈的第一次迭代前執行一次。在每次迭代時,都會檢查條件。如果條件評估為 true
,則執行迴圈的主體,否則就終止迴圈。每次迭代結束時都會執行遞增陳述式。
這裡有個簡單的 for 迴圈範例:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
fmt.Printf("%d ", i)
}
}
# Output
0 1 2 3 4 5 6 7 8 9
與 C、C++ 和 Java 等其他語言不同,Go 的 for 迴圈不包含括號,但大括號 {}
是必需的。
注意,for
迴圈的初始化和遞增陳述式都是非必要的,可以省略
省略初始化陳述式
package main import "fmt" func main() { i := 2 for ;i <= 10; i += 2 { fmt.Printf("%d ", i) } }
# Output 2 4 6 8 10
省略遞增陳述式
package main import "fmt" func main() { i := 2 for ;i <= 20; { fmt.Printf("%d ", i) i *= 2 } }
# Output 2 4 8 16
注意,在上面的
for
迴圈範例中,你也可以省略分號,並這樣寫:package main import "fmt" func main() { i := 2 for i <= 20 { fmt.Printf("%d ", i) i *= 2 } }
上面的
for
迴圈與其他語言中的while
迴圈類似。Go 沒有while
迴圈,因為我們可以使用for
輕鬆表示white
迴圈。最後,在 Golang 中你也可以省略
for
迴圈的條件。這會給你一個無限迴圈:package main func main() { // Infinite Loop for { } }
break 陳述式
你可以使用 break
陳述式在正常終止之前中斷循環。這裡有個範例:
package main
import "fmt"
func main() {
for num := 1; num <= 100; num++ {
if num%3 == 0 && num%5 == 0 {
fmt.Printf("First positive number divisible by both 3 and 5 is %d\n", num)
break
}
}
}
# Output
First positive number divisible by both 3 and 5 is 15
continue 陳述式
continue
陳述式用於中途停止執行迴圈主體,並繼續執行迴圈的下一個迭代。
package main
import "fmt"
func main() {
for num := 1; num <= 10; num++ {
if num%2 == 0 {
continue;
}
fmt.Printf("%d ", num)
}
}
# Output
1 3 5 7 9
結論
在本文中,你學到了如何在 Golang 中使用流程控制陳述式,如 if
、switch
和 for
。