Is there no XOR operator for booleans in golang?
Asked Answered
L

3

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.

Loathsome answered 12/4, 2014 at 3:22 Comment(0)
C
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
Clevey answered 12/4, 2014 at 3:26 Comment(5)
why isn't there one built in? I find it so weird.Loathsome
While your definition of XOR is true, I'd go with x != yBookmaker
@Jsor Doh. I miss the obvious far too often :| Updated.Clevey
You could say that Go does have an exclusive-or operator for bool, and it's spelled !=.Lemley
all good until you need something like boolVar XOR boolFunc()Czarevitch
E
128

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.

Endure answered 30/11, 2014 at 7:39 Comment(2)
Clearly (s == "test") != ( s == "not test") does not workSyndetic
@Syndetic 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 trueUruguay
C
1

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

Cousteau answered 23/1 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.