🪄 go-safecast: safe numbers conversion
go-safecast solves the type conversion issues in Go
In Go, integer type conversion can lead to a silent and unexpected behavior and errors if not handled carefully.
This package helps to convert any number to another, and report an error when if there would be a loss or overflow in the conversion
Usage
package main
import (
"fmt"
"math"
"github.com/ccoveille/go-safecast"
)
func main() {
var a int
a = 42
b, err := safecast.ToUint8(a) // everything is fine
if err != nil {
fmt.Println(err)
}
fmt.Println(b)
// Output: 42
a = 255 + 1
_, err = safecast.ToUint8(a) // 256 is greater than uint8 maximum value
if err != nil {
fmt.Println(err)
// Output: conversion issue: 256
…