使用值的切片作为switch语句的case进行匹配

14

我知道你可以使用逗号将多个值分隔开,在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")
    }
}

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

我的问题是,能否使用多个值的切片作为case(s)在switch语句中匹配多个值?我知道可以使用if else语句和一个'Contains(slice, element)'函数来实现,只是想知道是否可能。

像这样的东西也许可以吗?

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")
    }
}

据我所知,这是不可能的。Go语言的switch只是一个if,当switch为空时,或者是一个if value ==,当它不为空时。 - Alex Netkachov
2
请查看语言规范:http://golang.org/ref/spec#Switch_statements - Volker
3个回答

14

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

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")
    }
}

2
如果您可以控制切片,那么您可以使用映射(maps)代替它们:
package main

func main() {
   var (
      value = 5
      low = map[int]bool{1: true, 2: true, 3: true}
      high = map[int]bool{4: true, 5: true, 6: true}
   )
   switch {
   case low[value]:
      println("matches 1,2 or 3")
   case high[value]:
      println("matches 4,5 or 6")
   }
}

如果所有的数字都在256以下,你可以使用字节:

package main
import "bytes"

func main() {
   var (
      value = []byte{5}
      low = []byte{1, 2, 3}
      high = []byte{4, 5, 6}
   )
   switch {
   case bytes.Contains(low, value):
      println("matches 1,2 or 3")
   case bytes.Contains(high, value):
      println("matches 4,5 or 6")
   }
}

0

不行,由于语言规范,你不能这样做。 最简单的方法是:

  1. 对于动态值,使用唯一集合(map[value]struct{})
  2. 对于静态值,在switch case中直接打印值

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接