I know you can match multiple values with the switch statement by separating values with commas:
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
My question is, can you match multiple values with the switch statement by using slice(s) of multiple values as case(s)? I know It can be done by using if else statements and a 'Contains(slice, element)' function, I am just wondering if its possible.
Something like this maybe?:
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")
}
}
A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError .
Go language supports two types of switch statements: Expression Switch. Type Switch.
Switch case starts from statement condition 1, her condition will be any value which we are comparing or some string and numeric value. If condition 1 matches then it will go for the execution of statement 1 and condition 2 matches then it will go execution of statement 2 and so on it will check for each condition.
A select will choose multiple valid options at random, while a switch will go in sequence (and would require a fallthrough to match multiple.)
The best you can get is probably this one:
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")
}
}
If you have control over the slices, you could just use maps instead:
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")
}
}
or if all the numbers are under 256, you can use bytes:
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With