通过使用值切片作为带有 switch 语句的 case 来匹配值

BAR*_*ARJ 5 matching go switch-statement slice

我知道您可以通过用逗号分隔值来将多个值与 switch 语句匹配:

func main() {
    value := 5
    switch value{
    case 1,2,3:
        fmt.Println("matches 1,2 or 3")
    case 4,5, 6:
        fmt.Println("matches 4,5 or 6")
    }
}
Run Code Online (Sandbox Code Playgroud)

http://play.golang.org/p/D_2Zp8bW5M

我的问题是,您可以通过使用多个值的切片作为 case(s) 来匹配多个值与 switch 语句吗?我知道它可以通过使用 if else 语句和“包含(切片,元素)”函数来完成,我只是想知道它是否可能。

可能是这样的?:

func main() {
    value := 5

    low := []int{1, 2, 3}
    high := []int{4, 5, 6}

    switch value {
    case low:
        fmt.Println("matches 1,2 or 3")
    case high:
        fmt.Println("matches 4,5 or 6")
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*hov 7

你能得到的最好的可能是这个:

package main

import "fmt"

func contains(v int, a []int) bool {
    for _, i := range a {
        if i == v {
            return true
        }
    }
    return false
}

func main() {
    first := []int{1, 2, 3}
    second := []int{4, 5, 6}

    value := 5
    switch {
    case contains(value, first):
        fmt.Println("matches first")
    case contains(value, second):
        fmt.Println("matches second")
    }
}
Run Code Online (Sandbox Code Playgroud)