在 golang 中布尔值没有 XOR 运算符吗?
我试图做一些类似 b1^b2的东西,但它说它不是为布尔型定义的。
b1^b2
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 -> (X || Y) && !(X && Y)
Or, more trivially as Jsor pointed out,
X xor Y <-> X != Y
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.
not equal to
xor