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")
}
相关推荐
「QT(C++)开发工程师」2 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天3 小时前
0 初识C++
开发语言·c++
FfHUCisI3 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI3 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
lemon_sjdk4 小时前
ObjectProperty
java·开发语言·算法
大模型码小白4 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh9504 小时前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区
「QT(C++)开发工程师」4 小时前
C++ std::move 详解
开发语言·c++
matlab代码4 小时前
基于matlab的玉米种子计数设计(GUI界面)【源码58期】
开发语言·matlab