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")
}
相关推荐
biter down4 分钟前
C++ 组合与继承:从设计本质到实战,吃透高内聚低耦合
开发语言·c++
灰灰勇闯IT4 分钟前
C语言实战:字符串元音字母提取器的实现与优化
c语言·开发语言
fantasy5_515 分钟前
C++11 核心特性实战博客
java·开发语言·c++
天若有情67344 分钟前
从构造函数到Vue3响应式:C++中“常量转特殊类型”的隐藏大招
开发语言·c++
计算机学姐1 小时前
基于Python的B站数据分析及可视化系统【2026最新】
开发语言·vue.js·python·信息可视化·数据挖掘·数据分析·推荐算法
沐知全栈开发1 小时前
《XHR.readyState详解及在JavaScript中的应用》
开发语言
黑金IT1 小时前
抢占GPU ECS方案节省60-90%的成本
golang·gpu服务器
qq_433554541 小时前
C++ 进阶动态规划(小明的背包3)
开发语言·c++·动态规划
YouEmbedded1 小时前
解码继承——代码复用与层次化设计
开发语言·c++·继承
这是个栗子1 小时前
【JS知识点总结】JavaScript 中的精确取整:Math.floor、Math.ceil 与 Math.round
开发语言·javascript·ecmascript