DEV Community

Cover image for Demystifying the int type in Go
Jethro Daniel
Jethro Daniel

Posted on

Demystifying the int type in Go

An integer can be defined as a whole number, in computer science an integer can be represented by different sizes, based on the number of bits used to represent them.

  1. 16Bits or 2Bytes Also called a short in many other langauges
  2. 32Bits or 4Bytes also called an int in many other langauges
  3. 64Bits or 8 Bytes also called a long in many other languages And the list goes on, some other languages have the concept of 128 bits

The Go programming language is very interesting especially with its various integer types. The Go programming languages as of today currently supports the following:

  1. int
  2. int8
  3. int16
  4. int32
  5. int64

Can you guess what are the sizes of the types ?

Well, lets see for ourself

func printAll(){
    fmt.Printf(" int %d,\n int8 %d, \n int16 %d,\n int32 %d, \n int64 %d",
        unsafe.Sizeof(int(0)),
        unsafe.Sizeof(int8(0)),
        unsafe.Sizeof(int16(0)),
        unsafe.Sizeof(int32(0)),
        unsafe.Sizeof(int64(0)))
}
Enter fullscreen mode Exit fullscreen mode

The result is
Result

Wow, coming from a C# background where an int is always 4 byte, seeing 8bytes for an int is mind boggling.

Digging into the Go int documentation, here is what it says

int is a signed integer type that is at least 32 bits in size

so what then does atleast mean ? Turns out that the size of the int type varies based on the CPU type, if it is a 32 bit CPU, then you have 4 bytes, if it is 64 bits then you expect 8 bytes.

This was quite interesting, especially coming from a C# background where an int is always 4bytes.

Go engineers, therefore should be careful when using the int type. If you intend to store a 64bit value, it is better you use an int64 type to avoid any weird outcome.

Also in high performance scenario where memory is a concern, always use the correct type.

Top comments (0)