-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
See these four methods on reflect.Value
:
- https://pkg.go.dev/reflect#Value.OverflowComplex
- https://pkg.go.dev/reflect#Value.OverflowFloat
- https://pkg.go.dev/reflect#Value.OverflowInt
- https://pkg.go.dev/reflect#Value.OverflowUint
For example, looking at OverflowInt
's godoc:
OverflowInt reports whether the int64 x cannot be represented by v's type. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
None of that needs a value, in my opinion - a type would suffice. The implementation seems to confirm that - only the "kind" and "type" are used, not the actual value.
So I think the methods should be added to Type
, with the same signature.
I noticed this because quite a few projects have code like reflect.Zero(typ).OverflowInt(x)
, when in fact it could just be typ.OverflowInt(x)
, saving the creation of a new value. For example, in encoding/json
: https://cs.opensource.google/go/go/+/refs/tags/go1.20.4:src/encoding/json/decode.go;l=799
As for users who have a reflect.Value
rather than a reflect.Type
, they could also replace val.OverflowInt(x)
with val.Type().OverflowInt(x)
, and we could consider deprecating the Value
methods in favor of the Type
methods after a few Go releases. I don't personally see a point in keeping eight methods around; .Type()
isn't enough characters to warrant a shortcut, and in my experience, most reflect users will need to get the reflect.Type
for other reasons.