Nani sweaty
Nani sweaty

Reputation: 41

GoLang, how to write a multi-line statement if condtion

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?

Upvotes: 0

Views: 6030

Answers (2)

icza
icza

Reputation: 417412

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?

Upvotes: 8

Grzegorz Żur
Grzegorz Żur

Reputation: 49161

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

Upvotes: 1

Related Questions