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)
}
相关推荐
apcipot_rain26 分钟前
C++开发 面试 1Day速通
开发语言·c++·面试
时间的情敌33 分钟前
Three.js GLTF 阀门 / 泵体模型加载、材质修改、状态联动(正常 / 故障 / 告警变色)
开发语言·javascript·three.js·材质
大数据技术派1 小时前
有了AI,你多久没有亲自写代码了?
后端
星恒随风1 小时前
从0实现C++ AI大模型接入SDK(七):Ollama本地模型部署、NDJSON流式响应与LLMManager模型管理
linux·开发语言·c++·人工智能·笔记
考虑考虑1 小时前
JDK27的LazyConstant
java·后端·java ee
知识搬运临时工2 小时前
加一层连接池,TPS 从 26438 掉到 12923
java·后端
琳少_2 小时前
java课堂笔记
java·开发语言·数据库·笔记
周末程序猿2 小时前
技术总结|OpenSpec 实战:如何先写规格,再让 AI 写代码
后端·ai编程
Brain 博览记3 小时前
脑机接口研究丨FPGA 5 毫秒完成运动想象分类
开发语言·论文阅读·人工智能·机器学习·fpga开发·分类·数据挖掘
计算机–阿拉升学长4 小时前
基于SpringBoot的番茄种植水肥一体化管理系统 — 系统设计与实现
java·spring boot·后端·mysql·vue·javaweb