liveBook · Manning

Integer wraparound

As explained in Go in Action, Second Edition

Integer wraparound is the behavior in which arithmetic outside an integer type's representable range produces a value obtained by cycling through its fixed-width bit representation.

Integer wraparound occurs when arithmetic exceeds a fixed-width integer’s range and the bit pattern cycles to the opposite boundary. Unsigned subtraction makes the behavior especially visible: subtracting one from zero produces the type’s maximum value. section 3.1.1

Use these implementation rules when choosing integer types and function parameters:

  • Expect wraparound at integer limits, with unsigned values particularly vulnerable because zero is their lower boundary. section 3.1.1
  • Do not use uint merely to signal that a function accepts positive values; converting a negative int can silently create a huge unsigned value. section 3.1.1
  • Accept a signed value and validate it explicitly when negative input should be rejected, returning an error instead of relying on conversion. section 3.1.1

Unsigned subtraction

With var u uint64 initialized to zero, u = u - 1 yields 18446744073709551615. The value is large because the fixed-width representation rolls backward from zero to its maximum. section 3.1.1

Listing 3.3 Subtracting from an unsigned integer
var u uint64 // 0
u = u - 1

fmt.Println(u) // output: 18446744073709551615

Inspect the runnable subtraction example showing uint64 wraparound. section 3.1.1

How Go in Action, Second Edition covers it

How deep it goes
Demonstrates bit-level boundary behavior and conversion consequences, then stops at validation guidance rather than broader arithmetic internals.
Examples
Uses uint64 subtraction, an unsigned-only function, negative literals, converted negative values, and explicit error checking.
What it assumes
Assumes familiarity with integer variables, function arguments, conversions, and basic signed-versus-unsigned distinctions.
What you can do after
Diagnose unexpected large unsigned values and design signed, validated function inputs that expose negative-value errors.
How it connects
Connects integer wraparound to unsigned integers, integer types, type conversion, function arguments, and input validation.

Also explained in

Compare how 3 books explain integer wraparound →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.