Go 语言 switch 语句的特点

发布于:2024-08-11 ⋅ 阅读:(142) ⋅ 点赞:(0)

在 Go 语言中,switch 语句设计得更加简洁和直观,因此不需要显式使用 break 语句来终止一个分支。这种设计决策源于 Go 语言的一些设计哲学和目标,主要包括:

  1. 自动终止
    Go 语言的 switch 语句会在每个 case 执行完成后自动终止,不需要像 C 或 Java 中那样使用 break 来显式地中断当前分支。这意味着你不需要担心遗漏 break 导致意外的“贯穿”(fall-through)行为。

  2. 避免“贯穿”
    在 Go 语言中,switch 语句的默认行为是结束当前 case 后自动跳出 switch 语句。这种设计可以减少因忘记添加 break 语句而导致的潜在错误。

  3. 显式 fallthrough
    如果你确实希望在一个 case 执行后继续执行下一个 case,可以使用 fallthrough 关键字。这样可以明确地指示编译器要进行“贯穿”,避免了无意中出现这种情况。

示例:

func main() {
	testSwitch(2)
}
func testSwitch(i int) {
	switch i {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
		fallthrough
	case 3:
		fmt.Println("three")
	case 4:
		fmt.Println("four")
	default:
		fmt.Println("none")
	}
}

# 输出:
two
three

在这个例子中,fallthrough 关键字使得 case 2 执行完成后,程序继续执行 case 3 的代码块。这与传统的 switch 语句中需要手动添加 break 的做法不同。

fallthrough 使用注意事项

1、fallthrough 只能用于普通的 case

fallthrough 不能用于 default 分支。它只能在普通的 case 分支中使用

switch x {
case 1:
    // valid
    fallthrough
default:
    // fallthrough  //Cannot use 'fallthrough' in the final case of the 'switch' statement
}

2、不能用于 case 中的代码块

switch x {
case 1:
    {
        fmt.Println("Case 1")
        //fallthrough // The 'fallthrough' statement is out of place
    }
case 2:
    fmt.Println("Case 2")
}

3、只能用于普通的 case 语句,而不能用于类型断言的 switch 语句中的 case

func printType(i interface{}) {
	switch i.(type) {
	case int:
		fmt.Println("Integer")
	case string:
		fmt.Println("String")
		//fallthrough //Cannot use 'fallthrough' in the type switch
	case bool:
		fmt.Println("Boolean")
	default:
		fmt.Println("Unknown type")
	}
}


网站公告

今日签到

点亮在社区的每一天
去签到