Integers, Signed and Unsigned
tally counts things: words, lines, letters. Counting means integers, and Go offers ten of them. Most of the time the answer is simply int, but you need to know why, and what happens at the edges.
The rule
Use
intby default; sizes are fixed, types never mix, and overflow wraps.
| Signed (can be negative) | Unsigned (0 and up) |
|---|---|
int8 −128 to 127 |
uint8 0 to 255 (alias byte) |
int16, int32 (alias rune), int64 |
uint16, uint32, uint64 |
int — 64 bits on 64-bit systems |
uint, uintptr |
Default to int. len returns an int, loop counters are int, and an untyped whole number like total := 0 becomes int. Reach for sized types only when a file format, protocol or huge array demands them.
Types never mix. An int and an int64 cannot be added until you convert one: total + int(extra). This feels strict, but it makes every size change visible.
Integer division truncates toward zero. 17 / 4 is 4, and -7 / 2 is −3, not −4. The remainder keeps the sign of the left side: -7 % 2 is −1.
Overflow wraps at run time.
var b uint8 = 255
b++
fmt.Println(b) // 0
var s int8 = 127
s++
fmt.Println(s) // -128No panic, no warning. The compiler only catches overflow in constants: var b uint8 = 256 is a compile error.
Literals can help readability: 1_000_000, 0xFF (hex), 0b1010 (binary), 0o755 (octal).
When should you pick an unsigned type on purpose? When the data is raw bytes (byte, []byte), bit patterns such as flags or hashes, or a format that says "unsigned 32-bit". For counting and arithmetic, stay with int.
The shortcut
For any integer expression, run three checks: same type? divides? can it leave its range?
Same type?
totalisint,linesisint. Good — no conversion needed.
That last line is why Go's own len returns int, not uint: subtraction on sizes must be allowed to go negative.
Drills
Answer fast — trust the rule.
What is 17 / 4 in Go when both are integers?
var n uint8 = 250 then n += 10. What is n?
var a int = 5; var b int64 = 2. What does a + b do?
What is -7 / 2 in Go?
Which line fails at compile time?
Remember
- Use
intby default; sizes are fixed, types never mix, and overflow wraps. - Shortcut: same type? divides? can it leave its range?
- Trap: run-time overflow and unsigned subtraction are silent.
