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

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")
}
}
- 3 回答
- 0 关注
- 185 浏览
添加回答
举报