英文:
short way of ORing all flags
问题
使用以下代码可以更简洁地实现你的需求:
const FlagAll = Flag1 | Flag2 | Flag3 | Flag4 | Flag5
这样,你可以将所有的标志位使用按位或运算符(|)进行组合。
英文:
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
答案1
得分: 2
由于您的所有标志都只包含一个1位,将该位向左移动,FlagAll将是下一个,但要减去1:
const (
Flag1 = 0
Flag2 = uint64(1) << iota
Flag3
Flag4
Flag5
FlagAll = uint64(1)<<iota - 1
)
测试一下:
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)
这将输出(在Go Playground上尝试):
00000000
00000010
00000100
00001000
00010000
00011111
请注意,如果您将最后一个常量左移并减去1,您将得到相同的值:
const FlagAll2 = Flag5<<1 - 1
但这需要显式包含最后一个常量(Flag5),而第一种解决方案不需要(您可以添加更多的标志,如Flag6,Flag7...,而FlagAll的值将保持正确,无需更改)。
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论