Skip to content

proposal: strconv: add generic integer variants #67110

@Jorropo

Description

@Jorropo

Proposal Details

I had an argument with @ldemailly on what is the least ugly to stringify a ~uint8 (typed iota enum) to a base ten number.
strconv.FormatUint(uint64(i), 10) is verbose so it seems people would enjoy using strconv.Itoa more, however Itoa is easy to use incorrectly, it may truncate on 32 bits platforms and is signed which might or might not be what you want to do. (search 13k results, this is popular)

I propose theses new functions:

// if new parse / format functions for new integers types are added, they would also be added there.
type integers interface{ uint | uint8 | uint16 | uint32 | uint64 | uintptr | int | int8 | int16 | int32 | int64 }

// ParseInteger is like [ParseInt] and [ParseUint], but it will error if s can't be parsed perfectly into T.
// It accept 2 <= base <= 36 or 0, see [ParseInt] for base 0 documentation.
func ParseInteger[T ~integers](s string, base int) (T, error)

// FormatInteger is like [FormatInt] and [FormatUint], it accept 2 <= base <= 36.
func FormatInteger[T ~integers](v T, base int) string

The idea is you don't bother thinking about what the best function is, what type conversion you need to do or what bitsize should be set to.
You just call ParseInteger or FormatInteger with the type you want, and let the type checker handles the tricky bits for you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions