Go语言编程基础 流程控制语句(二)(完结)

switch

switch是编写一连串if-else语句的简便方法,它运行第一个值等于条件表达式的case语句。

Go只运行选定的case,而非之后所有的case。Go自动提供了每个case后面所需的break语句。除非以fallthrough语句结束,否则分支会自动终止。 并且,Go的switch的case无需为常量,且取值不必为整数。

package main

import "fmt"

func main()  {
  switch i := 0; i {
  case 1:
    fmt.Println("one")
    fallthrough
  case 2:
    fmt.Println("two")
    fallthrough
  default:
    fmt.Println("other")
  }
}

switch的求值顺序

switch的case语句从上到下顺次执行,直到匹配成功时为止。

没有条件的switch

没有条件的switch与switch true相同。
这种形式可以令长串if-then-else更清晰。

package main

import "fmt"

func main()  {
  i := 0
  switch {
  case i == 0:
    fmt.Println("zero")
  case i > 0:
    fmt.Println("positive")
  case i < 0:
    fmt.Println("negative")
  }
}

def

defer 语句会将函数推迟到外层函数返回之后执行。
推迟调用的函数其参数会立即求值,但直到外层函数返回前该函数都不会被调用。

package main

import "fmt"

func main()  {
  defer fmt.Println("world")
  fmt.Println("hello")
}

defer栈

package main

import "fmt"

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

学习源:Go指南

猜你喜欢

转载自blog.csdn.net/qq_32165041/article/details/83828232