上篇:GO——學習筆記(二)
下篇:GO——學習筆記(四)
參考:
https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.3.md
示例代碼——go_2
https://github.com/jiutianbian/golang-learning/blob/master/go_2/main.go
一、go流程控制語句
-
if語句
x := 1 if x < 3 { fmt.Println("x 小于 3") } else if x == 3 { fmt.Println("x 等于 3") } else { fmt.Println("x 大于 3") } //在if的條件判斷語句里面允許聲明一個變量,這個變量的作用域只能在該條件邏輯塊內,其他地方不起作用了z if y := 3; y < 3 { fmt.Println("y 小于 3") } else if y == 3 { fmt.Println("y 等于 3") } else { fmt.Println("y 大于 3") } // fmt.Println(y) -
for語句
for i := 0; i < 5; i++ { fmt.Println("i:", i) } //省略表達式,類似其他語言的while功能 a := 0 for a < 5 { fmt.Println("a:", a) a++ } //運用break跳出循環(huán) for b := 0; b < 5; b++ { if b == 1 { break } fmt.Println("b:", b) } // break打印出來0 //運用continue跳出本次循環(huán) for c := 0; c < 5; c++ { if c == 1 { continue } fmt.Println("c:", c) } // continue打印出來0,2,3,4 //用for語句,來迭代string\切片\字典等類型 m := map[string]int{"E": 1, "F": 2} for k, v := range m { fmt.Println("k:v=", k, v) } -
switch語句
i := 1 switch i { case 1: fmt.Println("1") case 2: fmt.Println("2") case 3: fmt.Println("3") default: fmt.Println("你好,大兄弟") } //switch中,每個case是默認是自帶break的,這與C語言不同,如果需要強制執(zhí)行后面的語句,需要添加fallthrough switch i { case 1: fmt.Println("1") fallthrough case 2: fmt.Println("2") fallthrough case 3: fmt.Println("3") fallthrough default: fmt.Println("你好,大兄弟") } -
goto語句
//用goto跳轉到必須在當前函數內定義的標簽,自我感覺,不建議頻繁使用goto,邏輯不太清晰,容易死循環(huán) d := 0 Here: //這行的第一個詞,以冒號結束作為標簽 fmt.Println(d) d++ if d < 5 { goto Here } //輸出 0,1,2,3,4 -
defer語句
func main() { /* defer語句 */ //defer語句 用來預定對一個函數的調用。它只能出現(xiàn)在一個函數中(假設是A函數),且只能調用另一個函數(假設是B函數),意味著在A函數結束返回時,延遲調用B函數,一般用于打開文件時的資源清理等工作。如果一個函數內部調用多個 defer 語句,則遵循后進先出的原則。 defer test_1() defer test_2() //輸出:在main函數的最后執(zhí)行,先輸出nihao,再輸出hahaha,后進先出。自我感覺,defer的功能有點java中finally的意思 } func test_1() { fmt.Println("hahaha") } func test_2() { fmt.Println("nihao") }