Actually you may implement this with a single switch
statement:
a, b, c, d, e, f := 1, 2, 3, 4, 5, 6
switch a {
case b, c, d, e, f:
fmt.Println("'a' matches another!")
default:
fmt.Println("'a' matches none")
}
Output of the above (try it on the Go Playground):
'a' matches none
Using switch
is the cleanest and fastest solution.
Another solution could be to list the values you want a
to compare to, and use a for
loop to range over them and do the comparison:
This is how it could look like:
match := false
for _, v := range []int{b, c, d, e, f} {
if a == v {
fmt.Println("'a' matches another!")
match = true
break
}
}
if !match {
fmt.Println("'a' matches none")
}
Output is the same. Try this one on the Go Playground. Although this is more verbose and less efficient, this has the advantage that the values to compare to can be dynamic, e.g. decided at runtime, while the switch
solution must be decided at compile time.
Also check related question: How do I check the equality of three values elegantly?