Search code examples
goconstantslogical-operators

short way of ORing all flags


With the following:

const (
    Flag1 = 0
    Flag2 = uint64(1) << iota
    Flag3      
    Flag4      
    Flag5      
)

is there a shorter/better way of doing, I want to OR them all:

const FlagAll = Flag1 | Flag2 | Flag3 | Flag4 | Flag5

Solution

  • Since all your flags contain a single 1 bit, shifting the bit to the left, FlagAll would be the next in the line but subtract 1:

    const (
        Flag1 = 0
        Flag2 = uint64(1) << iota
        Flag3
        Flag4
        Flag5
        FlagAll = uint64(1)<<iota - 1
    )
    

    Testing it:

    fmt.Printf("%08b\n", Flag1)
    fmt.Printf("%08b\n", Flag2)
    fmt.Printf("%08b\n", Flag3)
    fmt.Printf("%08b\n", Flag4)
    fmt.Printf("%08b\n", Flag5)
    fmt.Printf("%08b\n", FlagAll)
    

    This will output (try it on the Go Playground):

    00000000
    00000010
    00000100
    00001000
    00010000
    00011111
    

    Note that you get the same value if you left shift the last constant and subtract 1:

    const FlagAll2 = Flag5<<1 - 1
    

    But this requires to explicitly include the last constant (Flag5) while the first solution does not require it (you may add further flags like Flag6, Flag7..., and FlagAll will be right value without changing it).