Golang中是否有when表达式

Golang中是否有when表达式 在 Kotlin 中有一个 when 表达式,其功能类似于 switch/case,但格式不同。Go 语言中是否有类似的东西?

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // 注意这里的代码块
        print("x is neither 1 nor 2")
    }
}
3 回复

我看不出和 switch/case 有什么区别…

PS: Go 中的所有条件语句都是语句。

更多关于Golang中是否有when表达式的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我可能选了一个不好的例子,下面的 when 用法很简洁,但用 case 就没那么流畅了:

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    60, 90, 120 -> print("x is in my favorite list") 
    else -> print("none of the above")
}

Go语言中没有直接的when表达式。Go使用switch语句来实现类似的功能,但语法和Kotlin的when有所不同。

Go的switch语句示例:

package main

import "fmt"

func main() {
    x := 2
    
    switch x {
    case 1:
        fmt.Println("x == 1")
    case 2:
        fmt.Println("x == 2")
    default:
        fmt.Println("x is neither 1 nor 2")
    }
}

Go的switch还支持更灵活的条件表达式:

switch {
case x == 1:
    fmt.Println("x == 1")
case x == 2:
    fmt.Println("x == 2")
default:
    fmt.Println("x is neither 1 nor 2")
}

以及多值匹配:

switch x {
case 1, 2, 3:
    fmt.Println("x is 1, 2, or 3")
case 4, 5:
    fmt.Println("x is 4 or 5")
default:
    fmt.Println("x is something else")
}

类型判断:

var i interface{} = "hello"

switch v := i.(type) {
case int:
    fmt.Printf("Integer: %v\n", v)
case string:
    fmt.Printf("String: %v\n", v)
default:
    fmt.Printf("Unknown type: %T\n", v)
}

Go的switch默认不会贯穿(不需要break),如果需要贯穿可以使用fallthrough关键字。

回到顶部