Jethro Daniel
Posted on May 3, 2021
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.
- 16Bits or 2Bytes Also called a short in many other langauges
- 32Bits or 4Bytes also called an int in many other langauges
- 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:
- int
- int8
- int16
- int32
- 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)))
}
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.
Posted on May 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.