How does Go handle integer overflow, division, and conversions between numeric types?
Question 34HardGo 1.22 to 1.25
var x int8 = 127
x++
fmt.Println(x) // -128: signed overflow wraps (two's complement), no panic
var u uint8 = 0
u--
fmt.Println(u) // 255
fmt.Println(-7 / 2, -7 % 2) // -3 -1: division truncates toward zero
lo := int64(math.MinInt64)
fmt.Println(lo / -1) // -9223372036854775808: overflow wraps, no panic
fmt.Println(int8(300 & 0xFF)) // 44
big := 300
fmt.Println(int8(big)) // 44: conversion keeps the low bits
neg := -1
fmt.Println(uint32(neg)) // 4294967295: conversion reinterprets the bits
// const c int8 = 128 // compile error: constant 128 overflows int8
// _ = 1 / 0 // compile error: division by zero
zero := 0
// _ = 1 / zero // runtime panic: integer divide by zero
fmt.Println(1.0 / float64(zero)) // +Inf: float division by zero doesn't panic
Rules:
- Integer arithmetic at run time wraps around silently, for both signed and unsigned types. The spec defines this behavior, unlike C, where signed overflow is undefined.
- Constant expressions are checked at compile time, so overflow there is an error.
- Integer division by zero panics at run time. Float division by zero gives
±InforNaN. %takes the sign of the dividend.- Shifting by a negative amount panics. Shifting by at least the bit width gives 0 (or -1 for right shifts of negative signed values).
For overflow-safe code, check before you add, or use math/bits.Add64 and Mul64, or math/big. int is 64-bit on 64-bit platforms, but don't assume that when data is serialized. Use fixed-size types in file formats and wire protocols.
More on Language Fundamentals & Types
- Q32What is the difference between a defined type (
type A B) and an alias (type A = B)? - Q33Arrays vs slices as values: what does this print?
- Q35How did loop variable semantics change in Go 1.22, and what does this print?
- Q36How do range-over-func iterators (Go 1.23) work? What does this print?
- Q37How do struct field alignment and padding work? What are the sizes of these structs?
- Q38What is the difference between a method value and a method expression? What does this print?