Is there no XOR operator for booleans in golang?

GoOperatorsLogical OperatorsXor

Go Problem Overview


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.

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharlie ParkerView Question on Stackoverflow
Solution 1 - Gouser2864740View Answer on Stackoverflow
Solution 2 - GoAlasdairView Answer on Stackoverflow