您的位置:首页 > 编程语言 > Go语言

Go语言中的switch用法实例分析

2015-02-26 10:22 1316 查看

这里你可能已经猜到 switch 可能的形式了。
case 体会自动终止,除非用 fallthrough 语句作为结尾。

复制代码 代码如下: package main
import (
 "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:
  // freebsd, openbsd,
  // plan9, windows...
  fmt.Printf("%s.", os)
 }
}

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

(例如,

switch i {
case 0:
case f():
}
当 i==0 时不会调用 f。)

复制代码 代码如下: package main
import (
 "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 链。

复制代码 代码如下: package main
import (
 "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.")
 }
}

希望本文所述对大家的Go语言程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Go语言 switch 用法