为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
喵喔喔 2021-10-25 20:31:06
我知道您可以通过用逗号分隔值来将多个值与 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 语句和“包含(切片,元素)”函数来完成,我只是想知道它是否可能。可能是这样的?: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")    }}

3 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

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


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

    }

}


查看完整回答
反对 回复 2021-10-25
?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

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

  1. 动态值使用唯一的集合(map[value]struct{})

  2. 直接在开关盒中打印静态值


查看完整回答
反对 回复 2021-10-25
?
慕标5832272

TA贡献1966条经验 获得超4个赞

如果您可以控制切片,则可以改用地图:


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

   }

}


查看完整回答
反对 回复 2021-10-25
  • 3 回答
  • 0 关注
  • 185 浏览
慕课专栏
更多

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号