### For
Go has only one looping construct, the for loop
func main(){ sum := 0; for i := 0; i < 10; i++ { sum += i } fmt.Println(sum) }
The init and post statements are optional
func main(){ sum := 1; for ; sum < 1000; { sum += sum } fmt.Println(sum) }
For is Go’s “while”
At that point you can drop the semicolons: C’s while is spelled for in Go.
func main(){ sum := 1; for sum < 1000 { sum += sum } fmt.Println(sum) }
### If
Go’s if statements are like its for loops.
func sqrt(x float64) string { if x < 0 { return sqrt(-x) + "i" } return fmt.Sprint(math.Sqrt(x)) } func main(){ fmt.Println(sqrt(2), sqrt(-4)) }
If with a short statement
func pow(x, n, lim float64) float64 { if v := math.Pow(x, n); v < lim { return v } else { fmt.Printf("%g >= %g\n", v, lim) } return lim } func main(){ fmt.Println( pow(3, 2, 10), pow(3, 3, 20), ) }
### Switch
A switch statement is a shorter way to write a sequence of if – else statements.
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.Println("%s.\n", os) } }
func main(){ fmt.Print("When's Saturday?") today := time.Now().Weekday() switch time.Saturday{ case today + 0: fmt.Println("Today.") case today + 1: fmt.Println("Tommorow.") case today + 2: fmt.Println("In two days.") default: fmt.Println("Too far away.") } }
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.") } }
### Defer
A defer statement defers the execution of a function until the surrounding function returns.
func main(){ defer fmt.Println("wrold") fmt.Println("hello") }
$ go build hello.go && ./hello
hello
wrold
Stacking defers
L Deferred function calls are pushed onto a stack.
func main(){ fmt.Println("counting") for i := 0; i < 10; i++ { defer fmt.Println(i) } fmt.Println("done") }
deferってのは使い方がよくわからんが、最初は参照しながら書けば問題なさそうです。