if 表達式1 { 分支1 } else if 表達式2 { 分支2 } else{ 分支3 }
Go語言規定與if
匹配的左括號{
必須與if和表達式
放在同一行,{
放在其餘位置會觸發編譯錯誤。 同理,與else
匹配的{
也必須與else
寫在同一行,else
也必須與上一個if
或else if
右邊的大括號在同一行數組
if條件判斷還有一種特殊的寫法,能夠在 if 表達式以前添加一個執行語句,再根據變量值進行判斷,其中score
只在當前的if else循環語句中生效,外部不可以使用這個變量oop
func ifDemo2() { if score := 65; score >= 90 { fmt.Println("A") } else if score > 75 { fmt.Println("B") } else { fmt.Println("C") } }
func forDemo() { for i := 0; i < 10; i++ { fmt.Println(i) } }
for循環的初始語句能夠被忽略,可是初始語句後的分號必需要寫學習
func forDemo2() { i := 0 for ; i < 10; i++ { fmt.Println(i) } }
for循環的初始語句和結束語句均可以省略設計
func forDemo3() { i := 0 for i < 10 { fmt.Println(i) i++ } }
死循環code
for { 循環體語句 }
for循環能夠經過break
、goto
、return
、panic
語句強制退出循環索引
Go語言中能夠使用for range
遍歷數組、切片、字符串、map 及通道(channel)。 經過for range
遍歷的返回值有如下規律:字符串
func switchDemo1() { finger := 3 switch finger { case 1: fmt.Println("大拇指") case 2: fmt.Println("食指") case 3: fmt.Println("中指") case 4: fmt.Println("無名指") case 5: fmt.Println("小拇指") default: fmt.Println("無效的輸入!") } }
一個分支能夠有多個值,多個case值中間使用英文逗號分隔it
func testSwitch3() { switch n := 7; n { case 1, 3, 5, 7, 9: fmt.Println("奇數") case 2, 4, 6, 8: fmt.Println("偶數") default: fmt.Println(n) } }
分支還能夠使用表達式,這時候switch語句後面不須要再跟判斷變量for循環
func switchDemo4() { age := 30 switch { case age < 25: fmt.Println("好好學習吧") case age > 25 && age < 35: fmt.Println("好好工做吧") case age > 60: fmt.Println("好好享受吧") default: fmt.Println("活着真好") } }
fallthrough
語法能夠執行知足條件的case的下一個case,是爲了兼容C語言中的case設計的編譯
func switchDemo5() { s := "a" switch { case s == "a": fmt.Println("a") fallthrough case s == "b": fmt.Println("b") case s == "c": fmt.Println("c") default: fmt.Println("...") } } //a //b
goto
語句經過標籤進行代碼間的無條件跳轉。goto
語句能夠在快速跳出循環、避免重複退出上有必定的幫助。Go語言中使用goto
語句能簡化一些代碼的實現過程。 例如雙層嵌套的for循環要退出時
func gotoDemo1() { var breakFlag bool for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { breakFlag = true break } fmt.Printf("%v-%v\n", i, j) } //外層for循環判斷 if breakFlag { break } } }
使用goto
語句能簡化代碼
func gotoDemo2() { for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { //設置退出標籤 goto breakFlag } fmt.Printf("%v-%v\n", i, j) } } breakFlag: fmt.Println("結束for循環") }
break
語句能夠結束for
、switch
和select
的代碼塊。
break
語句還能夠在語句後面添加標籤,表示退出某個標籤對應的代碼塊,標籤要求必須定義在對應的for
、switch
和 select
的代碼塊上
func breakDemo1() { BREAKDEMO1: for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { break BREAKDEMO1 } fmt.Printf("%v-%v\n", i, j) } } fmt.Println("...") }
func continueDemo() { //forloop1: for i := 0; i < 10; i++ { forloop2: for j := 0; j < 10; j++ { if i == 2 && j == 2 { continue forloop2 } fmt.Printf("%v-%v\n", i, j) } } }
package main import ( "fmt" ) func main() { for i := 1; i < 10; i++ { for j := 1; j <= i; j++ { fmt.Printf("%v*%v=%v\t", j, i, i*j) } fmt.Println() } }