基本的 for 循环包含三个由分号分开的组成部分:

    1. 初始化语句:在第一次循环执行前被执行
    2. 循环条件表达式:每轮迭代开始前被求值
    3. 后置语句:每轮迭代后被执行

    if 语句

    1. import (
    2. "fmt"
    3. "math"
    4. )
    5. func sqrt(x float64) string {
    6. if x < 0 {
    7. return sqrt(-x) + "i"
    8. }
    9. return fmt.Sprint(math.Sqrt(x))
    10. }
    11. func main() {
    12. fmt.Println(sqrt(2), sqrt(-4))
    13. }

    就像 for 循环一样,Go 的 if 语句也不要求用 ( ) 将条件括起来,同时, { } 还是必须有的。

    if 的便捷语句

    1. package main
    2. import (
    3. "fmt"
    4. "math"
    5. )
    6. func pow(x, n, lim float64) float64 {
    7. if v := math.Pow(x, n); v < lim {
    8. return v
    9. }
    10. return lim
    11. }
    12. fmt.Println(
    13. pow(3, 3, 20),
    14. )
    15. }

    在 if 的便捷语句定义的变量同样可以在任何对应的 else 块中使用。

    switch 语句

    1. package main
    2. import (
    3. "fmt"
    4. "runtime"
    5. )
    6. func main() {
    7. fmt.Print("Go runs on ")
    8. switch os := runtime.GOOS; os {
    9. case "darwin":
    10. fmt.Println("OS X.")
    11. case "linux":
    12. fmt.Println("Linux.")
    13. default:
    14. // freebsd, openbsd,
    15. // plan9, windows...
    16. fmt.Printf("%s.", os)
    17. }
    18. }

    在 if 的便捷语句定义的变量同样可以在任何对应的 else 块中使用。

    switch 的执行顺序: 条件从上到下的执行,当匹配成功的时候停止。

    1. package main
    2. import (
    3. "fmt"
    4. "time"
    5. )
    6. func main() {
    7. today := time.Now().Weekday()
    8. switch time.Saturday {
    9. case today + 0:
    10. fmt.Println("Today.")
    11. case today + 1:
    12. fmt.Println("Tomorrow.")
    13. case today + 2:
    14. fmt.Println("In two days.")
    15. default:
    16. fmt.Println("Too far away.")
    17. }
    18. }

    defer 语句

    1. package main
    2. import "fmt"
    3. func main() {
    4. // 2. 在输出 world
    5. defer fmt.Println("world")
    6. // 1. 先输出 hello
    7. fmt.Println("hello")
    8. }

    defer 栈

    延迟的函数调用被压入一个栈中。当函数返回时, 会按照后进先出的顺序调用被延迟的函数调用。

    1. package main
    2. import "fmt"
    3. func main() {
    4. fmt.Println("counting")
    5. for i := 0; i < 10; i++ {
    6. defer fmt.Println(i)
    7. }
    8. }