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")
}
相关推荐
雪的季节2 分钟前
C++ 运行时多态 vs 编译时多态
开发语言
chushiyunen4 分钟前
php笔记、下载安装等
开发语言·笔记·php
Xin_ye100866 分钟前
C# 零基础到精通教程 - WPF 深度专题:自定义布局与性能优化
开发语言·c#·wpf
努力努力再努力wz6 分钟前
【C++高阶数据结构系列】:跳表 SkipList 详解:多层索引、随机晋升与C++ 完整实现(附跳表实现的源码)
开发语言·数据结构·数据库·c++·redis·缓存·skiplist
更深兼春远8 分钟前
scala基于IDEA部署
开发语言·scala·intellij-idea
AIFQuant9 分钟前
贵金属投资 APP 开发:实时报价、图表、提醒与交易数据全链路
开发语言·前端·websocket·金融·web app
小七在进步10 分钟前
C语言:编译与链接
c语言·开发语言
shuoshuohaohao11 分钟前
《JavaScript》
开发语言·前端·javascript
ch.ju13 分钟前
Java程序设计(第3版)第四章——私有属性
java·开发语言
Cloud_Shy61817 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第二章 Item 13 - 16)
c语言·开发语言·网络·笔记·python·编辑器