golang示例:switch

Go 复制代码
package main

import "fmt"

func main() {
	var day int
	fmt.Println("输入 1 至 7 中的一数字以获取是星期几:")
	fmt.Scan(&day)
	switch day {
	case 1:
		fmt.Println("Monday")
	case 2:
		fmt.Println("Tuesday")
	case 3:
		fmt.Println("Wednesday")
	case 4:
		fmt.Println("Thursday")
	case 5:
		fmt.Println("Friday")
	case 6:
		fmt.Println("Saturday")
	case 7:
		fmt.Println("Sunday")
	default:
		fmt.Println("输入无效,请输入 1 到 7 的数字。")
	}
}

在 Go 中,fallthrough 允许继续执行下一个 case,即使条件不满足:

Go 复制代码
package main

import "fmt"

func main() {
	var value int
	fmt.Println("输入 1 到 3 的数字:")
	fmt.Scan(&value)
	switch value {
	case 1:
		fmt.Println("This is 1")
		fallthrough
	case 2:
		fmt.Println("This is 2")
	case 3:
		fmt.Println("This is 3")
	default:
		fmt.Println("输入无效,请输入 1 到 3 的数字。")
	}
}

如果多个 case 如果逻辑相同,可以合并:

Go 复制代码
package main

import "fmt"

func main() {
	var value int
	fmt.Println("输入 1 至 5 中的一个数字:")
	fmt.Scan(&value)
	switch value {
	case 1, 2, 3:
		fmt.Println("This is either 1, 2, or 3")
	case 4:
		fmt.Println("This is 4")
	case 5:
		fmt.Println("This is 5")
	default:
		fmt.Println("Other number")
	}
}

Go 的 switch 还有一种特殊形式:

bash 复制代码
switch value := x.(type) {}

Type Switch,类型 switch,它通常配合接口使用。

Go 复制代码
package main

import "fmt"

func printType(value interface{}) {
	switch v := value.(type) {
	case int:
		fmt.Println("整数:", v)
	case string:
		fmt.Println("字符串:", v)
	case bool:
		fmt.Println("布尔值:", v)
	case float64:
		fmt.Println("浮点数:", v)
	default:
		fmt.Println("其他类型")
	}
}

func main() {
	printType(55)
	printType("Golang")
	printType(true)
	printType(3.1415)
}
相关推荐
传奇开心果编程32 分钟前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
新时代牛马41 分钟前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
swordbob44 分钟前
ReentrantLock 与 AQS 完整学习手册
java·开发语言
白山编程大哥2 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
shmily麻瓜小菜鸡2 小时前
JavaScript / TypeScript 易踩坑知识点 —— 异步编程类
开发语言·javascript·typescript
七夜zippoe3 小时前
为什么 2026 年每个 Java 团队都该懂 AI Agent
java·开发语言·人工智能
znnnk3 小时前
【Python】GUI 开发从入门到实战(三):PyQt/PySide 进阶之路
开发语言·python·pyqt
Despacito10063 小时前
Java后端性能探查工具速查表
java·开发语言
IT_陈寒4 小时前
Python的多线程就是个假把式,我算是体验到了
前端·人工智能·后端