Reputation: 5199
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.
Upvotes: 111
Views: 107265
Reputation: 1
// Simple XOR gate
if (somethingA != nil) != (somethingB != nil) {
//DoSomething
}
Upvotes: 0
Reputation: 48693
As other have mentioned, the way to exclusive-OR two boolean values to is check if they are not equal to one another.
On another note, the XOR operator (^
) can work on integers as a binary operator.
package main
import "fmt"
type Bool bool
func (b Bool) String() string {
if b {
return "T"
} else {
return "F"
}
}
func main() {
// Variable swap
a, b := 3, 7
a, b = b, a
fmt.Println(a, b) // 7, 3
// XOR swap
a ^= b
b ^= a
a ^= b
fmt.Println(a, b) // 3, 7
// Boolean "XOR"
fmt.Printf("T XOR T = %v\n", Bool(true != true)) // F
fmt.Printf("T XOR F = %v\n", Bool(true != false)) // T
fmt.Printf("F XOR T = %v\n", Bool(false != true)) // T
fmt.Printf("F XOR F = %v\n", Bool(false != false)) // F
}
Upvotes: 0
Reputation: 1100
Go support bitwise operators as of today. In case someone came here looking for the answer.
Upvotes: 3
Reputation: 14131
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.
Upvotes: 137
Reputation: 61975
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
Upvotes: 160