// code_004_process_control project main.go
package main
import (
"fmt"
"time"
)
func main() {
//if語句
if a := 3; a > 3 {
fmt.Println("a >3")
} else if a == 3 {
fmt.Println("a==3")
} else {
fmt.Println("error")
}
fmt.Println("\n============\n")
//switch語句1
switch score := 90; score {
case 80, 90, 100:
fmt.Println("優(yōu)秀")
case 50, 60, 70:
fmt.Println("及格")
default:
fmt.Println("差")
}
//switch語句2
var score int = 90
switch score {
case 80, 90, 100:
fmt.Println("優(yōu)秀")
case 50, 60, 70:
fmt.Println("及格")
default:
fmt.Println("差")
}
//switch語句3
switch s3 := 90; {
case s3 >= 90:
fmt.Println("優(yōu)秀")
case s3 >= 80:
fmt.Println("良好")
default:
fmt.Println("一般")
}
fmt.Println("\n============\n")
//最簡單的無限循環(huán)
for {
time.Sleep(3 * time.Second)
fmt.Println("for循環(huán)結束")
break
} //相當于python中while True: java中的for(;;){}
//for循環(huán)
var i, sum int
for i = 1; i <= 100; i++ {
fmt.Printf("i=%d\n", i) //Printf()格式化輸出,Println()無法格式化
sum += i
}
fmt.Println("sum =", sum)
//for ... range...
s := "abc"
for i := range s { //支持str/array/slice/map--->>只能獲取到index的值
fmt.Printf("%c\n", s[i])
}
for _, c := range s { //忽略index
fmt.Printf("%c\n", c)
}
for i, c := range s {
fmt.Printf("第%d個值為:%c\n", i, c)
}
//for ... break 或者continue
for i := 0; i < 5; i++ {
if i == 2 {
fmt.Printf("i== 2時 跳出本次循環(huán)")
break
}
fmt.Println(i)
}
for i := 0; i < 5; i++ {
if 2 == i {
fmt.Println("哈哈,你看不到我,你真2")
continue
}
fmt.Println(i)
} //備注:break 可以用for、switch、select,而continue僅能用于for循環(huán)
//goto,用goto跳轉到必須在當前函數(shù)內定義的標簽:
fmt.Println("\n============\n")
for i := 0; i < 5; i++ {
for {
fmt.Println(i)
goto LABEL //跳轉到標簽LABEL,從標簽處,執(zhí)行代碼
}
}
fmt.Println("Let's see goto LABEL!!!")
LABEL:
fmt.Println("it is over")
}
網站名稱:Go語言中的控制語句
網頁鏈接:
http://weahome.cn/article/pjpecd.html