• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Go语言教程:switch分支结构

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

返回Go语言教程首页

概念简介

switch是多分支情况时快捷的条件语句。

例程代码


package main

import "fmt"
import "time"

func main() {

    // 一个基本的 `switch`。
    i := 2
    fmt.Print("write ", i, " as ")
    switch i {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    case 3:
        fmt.Println("three")
    }

    // 在同一个 `case` 语句中,你可以使用逗号来分隔多个表
    // 达式。在这个例子中,我们还使用了可选的
    // `default` 分支。
    switch time.Now().Weekday() {
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend")
    default:
        fmt.Println("It's a weekday")
    }

    // 不带表达式的 `switch` 是实现 if/else 逻辑的另一种
    // 方式。这里还展示了 `case` 表达式也可以不使用常量。
    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("It's before noon")
    default:
        fmt.Println("It's after noon")
    }

    // 类型开关 (`type switch`) 比较类型而非值。可以用来发现一个接口值的
    // 类型。在这个例子中,变量 `t` 在每个分支中会有相应的类型。
    whatAmI := func(i interface{}) {
        switch t := i.(type) {
        case bool:
            fmt.Println("I'm a bool")
        case int:
            fmt.Println("I'm an int")
        default:
            fmt.Printf("Don't know type %T\n", t)
        }
    }
    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")
}

执行&输出


$ go run switch.go
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

课程导航

学习上一篇:Go语言教程:if/else条件判断    学习下一篇:Go语言教程:数组

相关资料

本例程github源代码:https://github.com/xg-wang/gobyexample/tree/master/examples/switch


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
Go语言教程:if-else条件判断发布时间:2022-05-14
下一篇:
Go语言教程:map/hash/dict发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap