Go if/else語句範例


在Go語言中的分支,ifelse是直接的。

所有的範例程式碼,都放在 F:\worksp\golang 目錄下。安裝Go程式設計環境請參考:/2/23/798.html

這裡有一個基本的例子。
一個if語句可以不用else語句。
語句可以在條件語句之前; 在此語句中宣告的任何變數在所有分支中都可用。
注意,Go語言中的條件不需要圍繞括號,但是大括號是必需的。

Go語言中沒有三元組,所以即使對於基本條件,也需要使用一個完整的if語句。

if-else.go的完整程式碼如下所示 -

package main

import "fmt"

func main() {

    // Here's a basic example.
    if 7%2 == 0 {
        fmt.Println("7 is even")
    } else {
        fmt.Println("7 is odd")
    }

    // You can have an `if` statement without an else.
    if 8%4 == 0 {
        fmt.Println("8 is divisible by 4")
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in all
    // branches.
    if num := 9; num < 0 {
        fmt.Println(num, "is negative")
    } else if num < 10 {
        fmt.Println(num, "has 1 digit")
    } else {
        fmt.Println(num, "has multiple digits")
    }
}

// Note that you don't need parentheses around conditions
// in Go, but that the braces are required.

執行上面程式碼,將得到以下輸出結果 -

F:\worksp\golang>go run if-else.go
7 is odd
8 is divisible by 4
9 has 1 digit