Go if_else語句
8. if-else 語句
if 是條件語句。if 語句的語法是
Copyif condition {
}
如果 condition
為真,則執行 {
和 }
之間的程式碼。
不同於其他語言,例如 C 語言,Go 語言裡的 { }
是必要的,即使在 { }
之間只有一條語句。
if 語句還有可選的 else if
和 else
部分。
if condition {
} else if condition {
} else {
}
if-else 語句之間可以有任意數量的 else if
。條件判斷順序是從上到下。如果 if
或 else if
條件判斷的結果為真,則執行相應的程式碼塊。 如果沒有條件為真,則 else
讓我們編寫一個簡單的程式來檢測一個數字是奇數還是偶數。
Copypackage main
import (
"fmt"
)
func main() {
num := 10
if num % 2 == 0 { //checks if number is even
fmt.Println("the number is even")
} else {
fmt.Println("the number is odd")
}
}
if num%2 == 0
語句檢測 num 取 2 的餘數是否為零。 如果是為零則列印輸出 "the number is even",如果不為零則列印輸出 "the number is odd"。在上面的這個程式中,列印輸出的是 the number is even
if
還有另外一種形式,它包含一個 statement
可選語句部分,該元件在條件判斷之前執行。它的語法是
if statement; condition {
}
讓我們重寫程式,使用上面的語法來查詢數字是偶數還是奇數。
Copypackage main
import (
"fmt"
)
func main() {
if num := 10; num % 2 == 0 { //checks if number is even
fmt.Println(num,"is even")
} else {
fmt.Println(num,"is odd" )
}
}
在上面的程式中,num
在 if
語句中進行初始化,num
只能從 if
和 else
中訪問。也就是說 num
的範圍僅限於 if
else
程式碼塊。如果我們試圖從其他外部的 if
或者 else
訪問 num
,編譯器會不通過。
讓我們再寫一個使用 else if
的程式。
package main
import (
"fmt"
)
func main() {
num := 99
if num <= 50 {
fmt.Println("number is less than or equal to 50")
} else if num >= 51 && num <= 100 {
fmt.Println("number is between 51 and 100")
} else {
fmt.Println("number is greater than 100")
}
}
在上面的程式中,如果 else if num >= 51 && num <= 100
為真,程式將輸出 number is between 51 and 100
。
一個注意點
else
語句應該在 if
語句的大括號 }
之後的同一行中。如果不是,編譯器會不通過。
讓我們通過以下程式來理解它。
Copypackage main
import (
"fmt"
)
func main() {
num := 10
if num % 2 == 0 { //checks if number is even
fmt.Println("the number is even")
}
else {
fmt.Println("the number is odd")
}
}
在上面的程式中,else
語句不是從 if
語句結束後的 }
同一行開始。而是從下一行開始。這是不允許的。如果執行這個程式,編譯器會輸出錯誤,
main.go:12:5: syntax error: unexpected else, expecting }
出錯的原因是 Go 語言的分號是自動插入。
在 Go 語言規則中,它指定在 }
之後插入一個分號,如果這是該行的最終標記。因此,在if語句後面的 }
會自動插入一個分號。
實際上我們的程式變成了
Copyif num%2 == 0 {
fmt.Println("the number is even")
}; //semicolon inserted by Go
else {
fmt.Println("the number is odd")
}
分號插入之後。從上面程式碼片段可以看出第三行插入了分號。
由於 if{…} else {…}
是一個單獨的語句,它的中間不應該出現分號。因此,需要將 else
語句放置在 }
之後處於同一行中。
我已經重寫了程式,將 else 語句移動到 if 語句結束後 }
的後面,以防止分號的自動插入。
package main
import (
"fmt"
)
func main() {
num := 10
if num%2 == 0 { //checks if number is even
fmt.Println("the number is even")
} else {
fmt.Println("the number is odd")
}
}
現在編譯器會很開心,我們也一樣 ?。