在golang中没有针对布尔值的异或(XOR)运算符。

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

Is there no XOR operator for booleans in golang?

问题

在Go语言中,没有专门用于布尔类型的异或(XOR)运算符。你无法直接使用b1^b2这样的语法进行异或运算,因为Go语言中的布尔类型不支持该操作。

英文:

Is there no XOR operator for booleans in golang?

I was trying to do something like b1^b2 but it said it wasn't defined for booleans.

答案1

得分: 143

没有。Go语言没有提供逻辑异或运算符(即布尔型的异或运算),而位异或运算符只适用于整数。

然而,可以使用其他逻辑运算符来重写异或运算。当忽略表达式(X和Y)的重新评估时,

X xor Y -> (X || Y) && !(X && Y)

或者,更简单地如Jsor指出的那样,

X xor Y <-> X != Y
英文:

There is not. Go does not provide a logical exclusive-OR operator (i.e. XOR over booleans) and the bitwise XOR operator applies only to integers.

However, an exclusive-OR can be rewritten in terms of other logical operators. When re-evaluation of the expressions (X and Y) is ignored,

X xor Y -&gt; (X || Y) &amp;&amp; !(X &amp;&amp; Y)

Or, more trivially as Jsor pointed out,

X xor Y &lt;-&gt; X != Y

答案2

得分: 119

使用布尔值时,异或操作可以简单地表示为:

if boolA != boolB {

}

在这个上下文中,"不等于"的操作与"异或"的功能相同:只有当一个布尔值为真,另一个布尔值为假时,该语句才会为真。

英文:

With booleans an xor is simply:

if boolA != boolB {

}

In this context not equal to performs the same function as xor: the statement can only be true if one of the booleans is true and one is false.

huangapple
  • 本文由 发表于 2014年4月12日 11:22:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/23025694.html
匿名

发表评论

匿名网友

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

确定