DEV Community

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

Posted on

2 2

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay