天天看點

Go if else8. if-else 語句

8. if-else 語句

if 是條件語句。if 語句的文法是

if condition {  
}           

如果

condition

為真,則執行

{

}

之間的代碼。

不同于其他語言,例如 C 語言,Go 語言裡的

{ }

是必要的,即使在

{ }

之間隻有一條語句。

if 語句還有可選的

else if

else

部分。

if condition {  
} else if condition {
} else {
}           

if-else 語句之間可以有任意數量的

else if

。條件判斷順序是從上到下。如果

if

else if

條件判斷的結果為真,則執行相應的代碼塊。 如果沒有條件為真,則

else

代碼塊被執行。

讓我們編寫一個簡單的程式來檢測一個數字是奇數還是偶數。

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")
    }
}           

if num%2 == 0

語句檢測 num 取 2 的餘數是否為零。 如果是為零則列印輸出 "the number is even",如果不為零則列印輸出 "the number is odd"。在上面的這個程式中,列印輸出的是

the number is even

if

還有另外一種形式,它包含一個

statement

可選語句部分,該元件在條件判斷之前運作。它的文法是

if statement; condition {  
}           

讓我們重寫程式,使用上面的文法來查找數字是偶數還是奇數。

package 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 &gt;= 51 && num &lt;= 100

為真,程式将輸出

number is between 51 and 100

一個注意點

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")
    }
}           

else

語句不是從

if

語句結束後的

}

同一行開始。而是從下一行開始。這是不允許的。如果運作這個程式,編譯器會輸出錯誤,

main.go:12:5: syntax error: unexpected else, expecting }           

出錯的原因是 Go 語言的分号是自動插入。

在 Go 語言規則中,它指定在

}

之後插入一個分号,如果這是該行的最終标記。是以,在if語句後面的

}

會自動插入一個分号。

實際上我們的程式變成了

if num%2 == 0 {  
      fmt.Println("the number is even") 
};  //semicolon inserted by Go
else {  
      fmt.Println("the number is odd")
}           

分号插入之後。從上面代碼片段可以看出第三行插入了分号。

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")
    }
}           

繼續閱讀