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")
}
相关推荐
Korloa11 分钟前
表达式(CSP-J 2021-Expr)题目详解
c语言·开发语言·数据结构·c++·算法·蓝桥杯·个人开发
yodala43 分钟前
C++中的内存管理(二)
开发语言·c++
屁股割了还要学1 小时前
【数据结构入门】排序算法:插入排序
c语言·开发语言·数据结构·算法·青少年编程·排序算法
1 小时前
JAVA-15 (2025.08.20学习记录)
java·开发语言·学习
im_AMBER1 小时前
学习日志39 python
开发语言·python·学习
郭京京1 小时前
mongodb基础
mongodb·go
Q_Q5110082852 小时前
python的校园研招网系统
开发语言·spring boot·python·django·flask·node.js·php
程序员爱钓鱼5 小时前
Go语言实战案例-使用SQLite实现本地存储
后端·google·go
江湖十年5 小时前
Go 1.25 终于迎来了容器感知 GOMAXPROCS
后端·面试·go
Cyclic10015 小时前
IOS购买订阅通知信息解析说明Java
java·开发语言·ios