Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading