108

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.

3 Answers 3

153

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
5
  • 17
    why isn't there one built in? I find it so weird. Commented Apr 12, 2014 at 4:08
  • 87
    While your definition of XOR is true, I'd go with x != y
    – Linear
    Commented Apr 12, 2014 at 4:22
  • 3
    @Jsor Doh. I miss the obvious far too often :| Updated. Commented Apr 12, 2014 at 4:27
  • 22
    You could say that Go does have an exclusive-or operator for bool, and it's spelled !=. Commented Apr 12, 2014 at 5:41
  • 3
    all good until you need something like boolVar XOR boolFunc() Commented Jul 2, 2019 at 6:07
130

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.

2
  • Clearly (s == "test") != ( s == "not test") does not work
    – Adonis
    Commented Feb 23, 2022 at 10:31
  • 5
    @Adonis it works. XOR returns true if an only if only 1 of the 2 operands are true, and in your expression there are always a true and a false results, and false != true is true, which is the same as false XOR true
    – phuclv
    Commented Apr 13, 2022 at 8:07
2

Go support bitwise operators as of today. In case someone came here looking for the answer.

Not the answer you're looking for? Browse other questions tagged or ask your own question.