As converts integer types in Go and reports values that do not fit in the destination type.
Why I built it
I wrote it after an integer from an external API was converted several times as it passed through our code. By the time it reached the last conversion, the original type was hard to trace and the destination type was too small.
A checked conversion makes the failure visible at that boundary. The caller can handle the error before an incorrect value reaches another part of the system.
Check a conversion
Version 2 requires Go 1.24 or newer. Install it with go get github.com/lunemec/as/v2.
package main
import (
"fmt"
"github.com/lunemec/as/v2"
)
func main() {
for _, n := range []int{127, 128} {
converted, err := as.T[int8](n)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(converted)
}
}
127 fits in an int8. The second conversion reports that 128 overflows it.
Reuse a slice buffer
Pass a destination slice to SliceTInto when you already have a buffer. The conversion writes into that buffer and reports the index of each overflow.
dst := make([]int8, 2)
err := as.SliceTInto(dst, []int{127, 128})
// dst is [127 0]. err identifies the overflow at index 1.