Senior · Go foundations

Integer width, overflow and representation

Does int always have64 bits, and do integer operations panic on overflow?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

Reveal a strong answer
  1. int width is implementation-dependent within the language's specified choices; use an explicit-width type when a wire format or persistence contract requires one. Parsing must check range and errors.

  2. Integer overflow behavior is defined by Go's integer rules and does not generally panic like a bounds check. A sum, size multiplication or length conversion can overflow before an allocation or validation step.

  3. Validate untrusted sizes before arithmetic using bounds that avoid performing the overflowing operation. Signed/unsigned conversions can change meaning, so do not cast a negative length to uint and expect it to become safe.

Common trap

Switching every size to uint does not remove overflow and can turn negative input into a huge positive number.

Try it

How do you check count × elementSize against a memory budget without overflowing the product?

Worked solution

After validating nonnegative count and positive elementSize, compare count to budget/elementSize before multiplying. Then validate target int/address-space constraints. Test the exact boundary, one over and negative parsed input.

Change the constraint

Where does an unchecked distance addition break an otherwise correct shortest-path algorithm?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.