A Tour of GO (2)--Flow of Control

  1. For
  • No parentheses and the {} are always required.
    for i:=0; i<10; i++ {
    sum +=i
    }
  • The init and post statements are optional
    sum :=1
    for ; sum < 1000; {
    sum +=sum
    }
  • For is Go's "while". You can drop the semicolons from above which will change to
    for sum < 1000 {
    sum +=sum
    }
    just like the "while" in c.
  • Forever
    for{
    }
  1. If
  • No parentheses and the {} are always required.
    if x < 0 {
    }
  • Short statements: to execute before the condition.
    if v := 1 ; v<10 {
    return v
    }
    • variables declared by short statement are only in the scope until the end of if(including else).
  • Switch
    switch os:=runtime.GOOS; os {
    case "linux":
    fmt.pritln(xxx)
    ....
    default:
    ...
    }
    • The evaluation is from top to bottom, and stop once one of the condition is true.
    • switch with no condition is the same as switch true
  1. Defer

    Defer funcs are pushed into a stack and executed in a last in first out order when the surrounding function returns.
    func main() {
    fmt.Println("counting")

       for i := 0; i < 10; i++ {
         defer fmt.Println(i)
       }
       fmt.Println("done")
    }
    

    output:
    counting
    done
    9
    8
    ...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容