Skip to content

proposal: spec: checked integer types #30613

Open
@ianlancetaylor

Description

@ianlancetaylor

As a simpler alternative to #30209, I propose that we add a new set of integer types that panic on overflow.

First a quick summary of some other languages, to the best of my knowledge:

  • C and C++: integer overflow is undefined.
  • Java and D: integer overflow wraps. This is also what Go does today.
  • Rust, Clojure, and Ada: integer overflow throws an exception.
  • Swift: integer overflow throws an exception but additional operators wrap: &+, &-, &*.
  • Haskell: integer overflow is implementation defined.
  • C#: integer overflow may be checked or wrapped by using the checked and unchecked keywords.
  • Python and Ruby: integers have unbounded size and cannot overflow.

Issues #19624 and #30209 argue that in Go integer overflow should panic. But today integer overflow wraps, and we cannot break existing code.

I propose that we add a new set of checked integer types. These will use a prefix o, for overflow. The types will be oint, oint8, oint16, oint32, oint64, ouint, ouint8, ouint16, ouint32, ouint64, ouintptr. We can also consider adding the type aliases obyte (= ouint8) and orune (= ouint32) although I'm not sure they are very important.

These new types act exactly like the corresponding types without the o prefix, except that if an addition, subtraction, multiplication, or division operation overflows, the result is a run-time panic.

Issue #30209 suggests adding a comma-ok form to detect integer overflow in an expression, as is also suggested in #6815. The main advantage of comma-ok for simple expressions is for a simpler implementation of multi-precision arithmetic, but for that use we have instead chosen to provide functions in the math/bits package. The main advantage of comma-ok for complex expressions is to permit switching between checked and wrapping arithmetic, but we already have wrapping arithmetic in the int type, and there is no realistic prospect of removing that from the language. So I do not think we need a comma-ok form. If there are other uses of comma-ok, this proposal still supports them, awkwardly, via a deferred function that calls recover.

There will as usual be no automatic conversion between existing types and the new types. This requirement of Go is the only way that this approach can work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions