Home > Blockchain >  Golang | How would I check if multiple boolean values are true in a single if statement?
Golang | How would I check if multiple boolean values are true in a single if statement?

Time:11-14

I'm making a program in Golang using the flag package, and I'm trying to check if more than one flag in a specific list is true. Right now, this is my solution:

List := 0

if *md5flag {
    List  
}
if *sha1flag {
    List  
}
if *sha256flag {
    List  
}
if *sha512flag {
    List  
}

if List > 1 {
    // Do stuff
    os.Exit(1)  
}

Would there be an easier way to do this, and by using a single if statement?

CodePudding user response:

If all you need is to check that at most one flag is set and exit immediately in that case, you can use a loop with short circuiting, though I'm not sure if it's more readable for just 4 values:

flags := []*bool{md5flag, sha1flag, sha256flag, sha512flag}
seenSetFlag := false
for _, f := range flags {
    if *f {
        if seenSetFlag {
            os.Exist(1)
        }
        seenSetFlag = true
    }
}

CodePudding user response:

Go doesn't have any conversion from bool to int, so you need to use an if-statement in some way.

I would do something like this

package main

import (
    "fmt"
)

func boolsToInt(flags... bool) int {
    value := 0
    for _, flag := range flags {
        if flag {
            value  
        }
    }
    return value
}

func main() {
    b1, b2, b3, b4 := false, true, true, false
    fmt.Println(boolsToInt(b1, b2, b3, b4))
}

CodePudding user response:

You could write something like

count = (flag1?1:0) (flag2?1:0)  (flag3?1:0)   (flag4?1:0);
if (count >= 2) { … }

Whether that is more readable or not is your decision. It’s certainly fewer lines of code. (In my whole career I’ve had once a situation where I counted whether at least two out of three conditions were true).

  • Related