What is ^0 in golang?

Issue

I am seeing ^0 in the code base.

Example:

type stat struct {
  ...
  min int64
  ...
}

newStat := stat{min: ^0}

What does ^0 mean?

Solution

According to the docs:

^x bitwise complement is m ^ x with m = "all bits set to 1" for

unsigned x and m = -1 for signed x

So ^x inverts each of the bits in x, eg. 0101 becomes 1010. This means that ^0 is the same as ~0 in other mainstream languages.

When using two’s complement to represent negative numbers (which most programming languages do), the value of the bitwise complement of zero (where all bits are 1) is -1. So this is a way to write:

newStat := stat{min: -1}

Answered By – Murilo Vasconcelos

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.