Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does type int exist in Go

Tags:

go

There's int, int32, int64 in Golang.

int32 has 32 bits,
int64 has 64 bits,
int has 32 or 64 or different number of bits according to the environment.

I think int32 and int64 will be totally enough for the program. I don't know why int type should exist, doesn't it will make the action of our code harder to predict?

And also in C++, type int and type long have uncertain length. I think it will make our program fragile. I'm quite confused.

like image 412
Wzzzz Avatar asked Feb 17 '17 07:02

Wzzzz


People also ask

What does int mean in go?

int is one of the available numeric data types in Go . int has a platform-dependent size, as, on a 32-bit system, it holds a 32 bit signed integer, while on a 64-bit system, it holds a 64-bit signed integer.

Is int and int32 same in Golang?

int is one of the available numeric data types in Go used to store signed integers. int32 is a version of int that only stores signed numeric values composed of up to 32 bits.

Which integer type provides higher accuracy in Golang?

int is the integer type which offers the fastest processing speeds. The initial (default) value for integers is 0 , and for floats this is 0.0 A float32 is reliably accurate to about 7 decimal places, a float64 to about 15 decimal places.

What data types does Golang use?

Go has three basic data types: bool: represents a boolean value and is either true or false. Numeric: represents integer types, floating point values, and complex types. string: represents a string value.


2 Answers

Usually each platform operates best with integral type of its native size.

By using simple int you say to your compiler that you don't really care about what bit width to use and you let him choose the one it will work fastest with. Note, that you always want to write your code so that it is as platform independent as possible...

On the other hand int32 / int64 types are useful if you need the integer to be of a specific size. This might be useful f.e. if you want to save binary files (don't forget about endiannes). Or if you have large array of integers (that will only reach up to 32b value), where saving half the memory would be significant, etc.

like image 199
Kupto Avatar answered Sep 18 '22 07:09

Kupto


Usually size of int is equal to the natural word size of target. So if your program doesn't care for the size of int (Minimal int range is enough), it can perform best on variety of compilers.

When you need a specific size, you can of course use int32 etc.

like image 33
Mohit Jain Avatar answered Sep 17 '22 07:09

Mohit Jain