Most programming languages use ~
to represent a unary bitwise-not operation. Go, by contrast, uses ^
:
fmt.Println(^1) // Prints -2
Why did the Go designers decide to break with convention here?
Most programming languages use ~
to represent a unary bitwise-not operation. Go, by contrast, uses ^
:
fmt.Println(^1) // Prints -2
Why did the Go designers decide to break with convention here?
Because ^x is equivalent to m ^ x with m = "all bits set to 1" for unsigned x and m = -1 for signed x. Says so in the spec.
It's similar to how -x is 0 - x
^
operator is similar to +
and -
operators. For example:
+x == +0x0 + x
+x == 0x0 + x
-x == -0x0 - x
-x == 0x0 - x
^x == ^0x0 ^ x
^x == 0xF ^ x
So ^0 ^ x
is equal to ^x
.
^0
doesn't change the value of ^x
in ^
operation in a similar manner that +0
doesn't change the value of +x
in +
operation.
© 2022 - 2025 — McMap. All rights reserved.