Search code examples
gosyntaxoperatorsconventions

Why does Go use ^ rather than ~ for unary bitwise-not?


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?


Solution

  • 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