Foreword
This article, " A tour of Go " Language Guide study notes.
surroundings
Control flow
for
Go only one loop structure for
cycle. for
No statement in parentheses.
1 2 3 4 5 6 7 8 9 10 11 12 13
package mainimport "fmt" func () { sum := 0 for i := 0 ; i < 10 ; i++ { sum += i } fmt.Println(sum) }
Front and rear statement may be omitted.
1 2 3 4 5 6 7 8 9 10 11 12 13
package main import "fmt" func () { sum := 1 for ; sum < 1000 ; { sum += sum } fmt.Println(sum) }
for
Statement may be in another language while
statement.
1 2 3 4 5 6 7 8 9 10 11 12 13
package mainimport "fmt" func () { sum := 1 for sum < 1000 { sum += sum } fmt.Println(sum) }
Infinite loop the loop condition is omitted.
1 2 3 4 5 6 7 8
package main func () { for { } }
if
if
No statement in parentheses.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package mainimport ( "fmt" "math" ) func sqrt (x float64 ) string { if x < 0 { return sqrt(-x) + "i" } return fmt.Sprint(math.Sqrt(x)) } func () { fmt.Println(sqrt(2 ), sqrt(-4 )) }
if
語句可以在條件之前執行一個簡單的語句,由這個語句定義的變數,其作用域只限於在該 if
語句之內。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package mainimport ( "fmt" "math" ) func pow (x, n, lim float64 ) float64 { if v := math.Pow(x, n); v < lim { return v } return lim } func main () { fmt.Println( pow(3 , 2 , 10 ), pow(3 , 3 , 20 ), ) }
在 if
的便捷語句定義的變數可以在對應的 else
區塊中使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
package mainimport ( "fmt" "math" ) func pow (x, n, lim float64 ) float64 { if v := math.Pow(x, n); v < lim { return v } else { fmt.Printf("%g >= %gn" , v, lim) } return lim } func main () { fmt.Println( pow(3 , 2 , 10 ), pow(3 , 3 , 20 ), ) }
switch
switch
語句的條件從上到下執行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package mainimport ( "fmt" "runtime" ) func main () { fmt.Print("Go runs on " ) switch os := runtime.GOOS; os { case "darwin" : fmt.Println("OS X." ) case "linux" : fmt.Println("Linux." ) default : fmt.Printf("%s." , os) } }
除非使用 fallthrough
語句,否則匹配成功會自動終止
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
package mainimport ( "fmt" "time" ) func main () { fmt.Println("When's Saturday?" ) today := time.Now().Weekday() switch time.Saturday { case today + 0 : fmt.Println("Today." ) case today + 1 : fmt.Println("Tomorrow." ) case today + 2 : fmt.Println("In two days." ) default : fmt.Println("Too far away." ) } }
沒有條件的 switch
語句同 switch true
一樣,用以替代長的 if-then-else
條件式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
package mainimport ( "fmt" "time" ) func main () { t := time.Now() switch { case t.Hour() < 12 : fmt.Println("Good morning!" ) case t.Hour() < 17 : fmt.Println("Good afternoon." ) default : fmt.Println("Good evening." ) } }