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)
}
相关推荐
Zane19941 小时前
多开几个线程,为什么算数字反而没变快?一文讲透 CPython 的 GIL
后端·python
个 人 练 习 生1 小时前
数据结构入门:算法复杂度
开发语言·数据结构·经验分享·学习·程序人生·算法
一只叫煤球的猫1 小时前
Spring AI 2.0 源码解析(二):Starter 如何自动装配 ChatClient ?
后端·面试·langchain
W_326001 小时前
Python-OpenCV边缘检测与阈值分割:Sobel、Scharr、Laplacian、Canny、全局与自适应阈值
开发语言·图像处理·python·opencv·机器学习
其实防守也摸鱼1 小时前
红队技能总结导图:从入门到精通的完整知识体系
开发语言·人工智能·学习·安全·web安全
聊浮游1 小时前
JAVA2026最新全套学习资料、学习路线
java·开发语言·jvm·mysql·spring·maven·idea
饼干哥哥1 小时前
重生之我是导演:爆改成「牛来版」黑客帝国?附3D预演台保姆级教程!
人工智能·后端·深度学习
MacroZheng1 小时前
完美替代 Navicat!这款内置 AI 的数据库工具,太香了!
java·后端·mysql
世界哪有真情2 小时前
AI 写代码两年多,我发现自己越来越"看不进去"了
前端·后端·ai编程