网络编程
位置:首页>> 网络编程>> Go语言>> golang switch语句的灵活写法介绍

golang switch语句的灵活写法介绍

作者:冷月醉雪  发布时间:2024-04-23 09:39:49 

标签:golang,switch

switch是很容易理解的,先来个代码,运行起来

看看你的操作系统是什么吧


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:
       fmt.Printf("%s", os)
   }
}

runtine运行时获取当前的操作系统,使用GOOS。还和if for之类的习惯一样,可以在前面声明赋值变量。我们就在这里来获取操作系统的信息了。


os := runtime.GOOS;

{}里的case比较容易理解。操作系统是 "darwin" 就打印"OS X.";操作系统是 "linux" 就打印"Linux";其他的都直接打印系统类别。

在go语言的switch中除非以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.")
   case "windows":
       fmt.Println("win")
       fallthrough
   default:
       fmt.Printf("%s", os)
   }
}

增加了当前的系统的case选项"windows",还在这个分支使用了fallghrough。

如果你再注释掉 fallthrough,或干脆删除 fallthrough,再运行,就会发现,那个穿透的效果没有了。

来源:https://blog.csdn.net/lengyuezuixue/article/details/79351269

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com