Go语言基础语法之Switch语句使用|豆包MarsCode AI刷题

128 阅读2分钟

在 Go 语言中,switch 语句是一种控制结构,用于简化多个条件的判断逻辑。与其他语言类似,switch 可以用来替代复杂的 if-else 语句,但它有一些 Go 语言特有的特性。以下是 Go 中 switch 语句的语法及用法介绍。 基本语法:

switch [表达式] {
case1:
    // 执行的代码块
case2:
    // 执行的代码块
default:
    // 默认执行的代码块(可选)
}
  • 表达式:可以是任何支持相等比较的值,也可以省略。

  • case 语句:每个 case 代表一个条件,当 switch 的表达式与 case 中的值匹配时,执行对应代码块。

  • default:当没有匹配的 case 时执行,可选。 在后端入门的AI练中学中,有这么一段代码:

package main

import (
	"fmt"
	"time"
)

func main() {

	a := 2
	switch a {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	case 4, 5:
		fmt.Println("four or five")
	default:
		fmt.Println("other")
	}

	t := time.Now()
	switch {
	case t.Hour() < 12:
		fmt.Println("It's before noon")
	default:
		fmt.Println("It's after noon")
	}
}

这段代码包含两个不同用途的 switch 语句,分别演示了 常规匹配型 switch 和条件型 switch的使用。 第一个Switch语句:

a := 2
switch a {
case 1:
    fmt.Println("one")
case 2:
    fmt.Println("two")
case 3:
    fmt.Println("three")
case 4, 5:
    fmt.Println("four or five")
default:
    fmt.Println("other")
}

用途: 这是一个匹配型 switch,根据变量 a 的值匹配对应的 case

执行逻辑: 变量 a 的值为 2,因此匹配 case 2,执行 fmt.Println("two")。 不需要显式 break,因为 Go 的 switch 在匹配到某个 case 后会自动结束,除非使用 fallthrough

多个值匹配case 4, 5 表示 45 时都执行同一个代码块。 默认分支default 在没有任何匹配时执行,但在这段代码中未被触发。

第二个Switch语句:

t := time.Now()
switch {
case t.Hour() < 12:
    fmt.Println("It's before noon")
default:
    fmt.Println("It's after noon")
}

用途: 这是一个 条件型 switch,没有表达式,每个 case 都是一个布尔条件,按顺序从上到下评估。 它类似于连续的 if-else 语句。

执行逻辑: 当前时间由 time.Now() 获取。 t.Hour() 返回当前时间的小时数。 如果当前小时小于 12,则匹配 case t.Hour() < 12,输出 "It's before noon",否则匹配 default

省略表达式的 switch:当 switch 省略表达式时,每个 case 必须是布尔类型的表达式。 条件匹配:只要第一个条件匹配成功,后续条件将被跳过。