Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Go have several different integer types?

Tags:

types

integer

go

I find it rather confusing that there are different integer types in Go. What is the necessity of defining these different categories, given that these distinctions are not present in many other major programming languages?

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr
like image 657
Morteza R Avatar asked Jul 07 '15 10:07

Morteza R


1 Answers

Go has two kinds of types:

  1. architecture dependent types such as int, uint, uintptr. and
  2. architecture independent types such as int32, int64 etc.

The architecture dependent types have the appropriate length for the machine on which the program runs:

  • an int is the default signed type: it takes 32 bit (4 bytes) on a 32 bit machine and 64 bit (8 bytes) on a 64 bit machine; the same goes for the unsigned uint.
  • uintptr is an unsigned integer large enough to store a pointer value.

The architecture independent types have fixed size (in bits) indicated by their names:

For integers the ranges are:

int8 (-128 -> 127)
int16 (-32768 -> 32767)
int32 (− 2,147,483,648 -> 2,147,483,647)
int64 (− 9,223,372,036,854,775,808 -> 9,223,372,036,854,775,807)

For unsigned integers:

uint8 (with alias byte, 0 -> 255)
uint16 (0 -> 65,535)
uint32 (0 -> 4,294,967,295)
uint64 (0 -> 18,446,744,073,709,551,615)

For floats:

float32 (+- 1O-45 -> +- 3.4 * 1038 )
(IEEE-754) float64 (+- 5 * 10-324 -> 1.7 * 10308 )

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.

Due to the fact that perfect accuracy is not possible for floats comparing them with == or != must be done very carefully!

like image 83
Endre Simo Avatar answered Nov 10 '22 03:11

Endre Simo