Wzzzz
Wzzzz

Reputation: 139

Why does type int exist in 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.

Upvotes: 13

Views: 3588

Answers (4)

Zyl
Zyl

Reputation: 3270

The root cause for this is array addressability. If you came into a situation where you needed to call make([]byte, 5e9) your 32 bit executable would be unable to comply, while your 64 bit executable could continue to run. Addressing an array with int64 on a 32 bit build is wasteful. Addressing an array with int32 on a 64 bit build is insufficient. Using int you can address an array to its maximum allocation size on both architectures without having to code a distinction using int32/int64.

Upvotes: 1

jch
jch

Reputation: 5651

In versions of Go up to 1.0, int was just a synonym for int32 — a 32-bit Integer. Since int is used for indexing slices, this prevented slices from having more than 2 billion elements or so.

In Go 1.1, int was made 64 bits long on 64-bit platforms, and therefore large enough to index any slice that fits in main memory. Therefore:

  • int32 is the type of 32-bit integers;
  • int64 is the type of 64-bit integers;
  • int is the smallest integer type that can index all possible slices.

In practice, int is large enough for most practical uses. Using int64 is only necessary when manipulating values that are larger than the largest possible slice index, while int32 is useful in order to save memory and reduce memory traffic when the larger range is not necessary.

Upvotes: 3

Mohit Jain
Mohit Jain

Reputation: 30489

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.

Upvotes: 6

Kupto
Kupto

Reputation: 2992

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.

Upvotes: 6

Related Questions