Lesson 7. Whole numbers
After reading lesson 7, you’ll be able to
- Use 10 types of whole numbers
- Choose the right type
- Use hexadecimal and binary representations
Go offers 10 different types for whole numbers, collectively called integers. Integers don’t suffer from the accuracy issues of floating-point types, but they can’t store fractional numbers and they have a limited range. The integer type you choose will depend on the range of values needed for a given situation.
Consider this
How many numbers can you represent with two tokens?
If the tokens are individually identifiable by position, there are four possible permutations. Both tokens, neither token, one token, or the other token. You could represent four numbers.
Computers are based on bits. A bit can either be off or on—0 or 1. Eight bits can represent 256 different values. How many bits would it take to represent the number 4,000,000,000?
Five integer types are signed, meaning they can represent both positive and negative whole numbers. The most common integer type is a signed integer abbreviated int:
The other five integer types are unsigned, meaning they’re for positive numbers only. The abbreviation for unsigned integer is uint:
When using type inference, Go will always pick the int type for a literal whole number. The following three lines are equivalent: