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)
}
相关推荐
chenbingjie_c6 小时前
C++ 进阶核心知识点总结:模板、内存分区、new/delete、内存池
开发语言·c++
噢,我明白了7 小时前
java中唯一键和幂等键的应用
java·后端
GreenTea7 小时前
我把 Agent 的 while 循环拆掉了:一种你可能没想到的 Agent 架构
前端·后端·架构
考虑考虑7 小时前
synchronized字符串常量
java·后端·java ee
Escalating_xu8 小时前
【C 语言】深入理解指针(1·下):指针运算、野指针、assert 与传址实战
java·c语言·开发语言
实心儿儿8 小时前
Qt — Qt 事件
开发语言·qt
周杰偷奶茶8 小时前
【Java】数据类型与变量
java·开发语言
code斗8 小时前
Java数据结构:堆详解
java·开发语言·数据结构
颜进强8 小时前
16 · NestJS LifecycleEvents 生命周期事件:五个钩子、三条边界,和 rag-server 的优雅停机
前端·后端·ai编程
重生之小比特8 小时前
【C++进阶】map和set
java·开发语言·c++