首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Go程序例子(7):Switch

Go程序例子(7):Switch

原创
作者头像
用户11078756
发布于 2024-12-08 13:53:52
发布于 2024-12-08 13:53:52
3450
举报
文章被收录于专栏:go程序例子go程序例子

Switch 语句可以在多个分支中表达条件判断。

代码语言:go
复制
package main

import (
    "fmt"
    "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")
    }
	// 类型 switch 是比较类型而非值的 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")
}

运行结果:

代码语言:javascript
复制
$ 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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档