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")
}
相关推荐
Joy T9 小时前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
专注仿真13 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
Best-Wishes13 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
代码不停14 小时前
自动化测试(java)
java·开发语言·selenium·自动化
鬼手点金15 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
爱上网的小舟15 小时前
星际战士2启动错误怎么办?5种游戏报错解决方法
开发语言·php
阿里嘎多学长16 小时前
2026-10-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管
wangchunyu11417 小时前
Python 数据可视化实战入门教程
开发语言·python·信息可视化
microrain17 小时前
读数是 1008,用电量是 8:SagooIoT 计算服务的增量口径与七种计算策略
物联网·golang·计算服务·sagooiot
林壮Allen18 小时前
用 Go 从零实现多 Agent 协作框架:两个让我踩坑的设计问题
go·ai编程