将所有标志进行逻辑或运算的简洁方式。

huangapple go评论78阅读模式
英文:

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),而第一种解决方案不需要(您可以添加更多的标志,如Flag6Flag7...,而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) &lt;&lt; iota
	Flag3
	Flag4
	Flag5
	FlagAll = uint64(1)&lt;&lt;iota - 1
)

Testing it:

fmt.Printf(&quot;%08b\n&quot;, Flag1)
fmt.Printf(&quot;%08b\n&quot;, Flag2)
fmt.Printf(&quot;%08b\n&quot;, Flag3)
fmt.Printf(&quot;%08b\n&quot;, Flag4)
fmt.Printf(&quot;%08b\n&quot;, Flag5)
fmt.Printf(&quot;%08b\n&quot;, 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&lt;&lt;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).

huangapple
  • 本文由 发表于 2022年9月26日 00:12:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73846014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定