Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are reasons to use a sized or unsigned integer type in go?

Tags:

go

Doing the go tour in chapter "Basics/Basic types" it says:

When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

What are those specific reasons? Can we name them all?

Other available ressources only talk about 32 and 64 bit signed and unsigned types. But why would someone use int types < 32 bit?

like image 636
Daniel Jurkovic Avatar asked Jan 14 '16 17:01

Daniel Jurkovic


1 Answers

If you cannot think of a reason not to use a standard int, you should use a standard int. In most cases, saving memory isn't worth the extra effort and you are probably not going to need to store that large values anyway.

If you are saving a very large number of small values, you might be able to save a lot of memory by changing the datatype to a smaller one, such as byte. Storing 8bit values in an int means we are storing 24bits of zeroes for every 8 bits of data, and thus, wasting a lot of space. Of course, you could store 4 (or maybe 8) bytes inside an int with some bitshift magic, but why do the hard work when you can let the compiler and the cpu do it for you?

If you are trying to do computations that might not fit inside a 32bit integer, you might want an int64 instead, or even bigint.

like image 83
Filip Haglund Avatar answered Nov 05 '22 02:11

Filip Haglund