0

I want to match bellow a value with b, c, d, e, f at once instead of writing multiple times like this.

My values are:

a = 11
b = 22
c = 33
d = 44
e = 55
f = 66

if a != b && a != c && a != d && a != e && a != f{
    // Do something
} else{
    // Do something else
}

Is actual working code method I have.

But I want to write it like

if a != b or c or d or e or f {print text}

a value should be used once in if statement. Is there is any easy method?

icza
  • 389,944
  • 63
  • 907
  • 827
Nani sweaty
  • 41
  • 1
  • 2
  • 1
    Related / possible duplicate of [Golang: How do I check the equality of three values elegantly?](https://stackoverflow.com/questions/37884152/golang-how-do-i-check-the-equality-of-three-values-elegantly/37889261#37889261) – icza Feb 01 '18 at 20:25

2 Answers2

8

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?

icza
  • 389,944
  • 63
  • 907
  • 827
  • its very helpful, – Nani sweaty Feb 02 '18 at 15:53
  • in this can we use simple method for comparing multiple values like a or b maches c, d, e, f switch a, b { case c, d, e, f: fmt.Println("'a or b' matches another!") default: fmt.Println("'a or b' matches none") } – Nani sweaty Feb 02 '18 at 16:04
  • Incidentally, the switch version can also be used as a compact method of checking an interface variable against a list of _types_. Example: https://play.golang.org/p/xjGQ-HNyjy3 – Kaedys Feb 02 '18 at 17:07
1

I would use switch statement

a := 11
b := 22
c := 33
d := 44
e := 55
f := 66
switch a {
case b, c, d, e, f:
default:
    fmt.Println("Hello, playground")
}
Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105