Go 语言基础教程:7.Switch 语句

在这篇教程中,我们将学习 Go 语言中的 switch 语句,它是条件分支的重要结构。我们将通过一个示例程序逐步解析 switch 的不同用法。


Go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {

    i := 2
    fmt.Print("Write ", i, " as ")
    switch i {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    case 3:
        fmt.Println("three")
    }

    switch time.Now().Weekday() {
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend")
    default:
        fmt.Println("It's a weekday")
    }

    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("It's before noon")
    default:
        fmt.Println("It's after noon")
    }

    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")
}
相关推荐
Sunshine for you26 分钟前
C++中的职责链模式实战
开发语言·c++·算法
@我漫长的孤独流浪40 分钟前
Python编程核心知识点速览
开发语言·数据库·python
添尹40 分钟前
Go语言基础之变量和常量
golang
qq_416018721 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563241 小时前
模板代码生成工具
开发语言·c++·算法
code 小楊1 小时前
yrb 1.5.0 正式发布:Python 极简国内下载加速与全景可视化终端体验!
开发语言·python
2401_831920741 小时前
C++代码国际化支持
开发语言·c++·算法
2401_851272991 小时前
自定义内存检测工具
开发语言·c++·算法
章鱼丸-2 小时前
DAY31 文件的拆分和写法
开发语言·python
左左右右左右摇晃2 小时前
Java并发——synchronized锁
java·开发语言