Go if else

8. if-else 語句

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

if condition {  
}

若是 condition 爲真,則執行 {} 之間的代碼。ide

不一樣於其餘語言,例如 C 語言,Go 語言裏的 { } 是必要的,即便在 { } 之間只有一條語句。code

if 語句還有可選的 else ifelse 部分。編譯器

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

if-else 語句之間能夠有任意數量的 else if。條件判斷順序是從上到下。若是 ifelse if 條件判斷的結果爲真,則執行相應的代碼塊。 若是沒有條件爲真,則 else 代碼塊被執行。it

讓咱們編寫一個簡單的程序來檢測一個數字是奇數仍是偶數。io

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 可選語句部分,該組件在條件判斷以前運行。它的語法是class

if statement; condition {  
}

讓咱們重寫程序,使用上面的語法來查找數字是偶數仍是奇數。import

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

在上面的程序中,numif 語句中進行初始化,num 只能從 ifelse 中訪問。也就是說 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")
}

分號插入以後。從上面代碼片斷能夠看出第三行插入了分號。

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

如今編譯器會很開心,咱們也同樣 ?。

相關文章
相關標籤/搜索