In some languages, the caret symbol (^) is used to represent exponentiation.
However, in Go, as in many C-like languages, it represents the bitwise
exclusive-or (XOR
) operation. It is recommended to carefully vet if the caret
is used for XOR or exponentiation.
The expression 2^32
in Go thus evaluates the number 34, not math.Pow(2, 32)
(or 1 << 32), and such patterns are likely erroneous. It is recommended to use
1 << EXP
(for 2^EXP) where EXP
is the exponent and the base is 2 or for any
base, math.Pow
from the standard library is recommended.
func main() {
// Prints 34, should be 1 << 32 instead. But make sure what's required:
// exponentiation or XOR'ing.
// NOTE: As programmers make a common mistake, we provide a lint for this but
// it should be audited before making any change.
fmt.Println(2 ^ 32)
}
func main() {
fmt.Println(1 << 32)
}