🪄 go-safecast: safe numbers conversion
Project purpose
In Go, integer type conversion can lead to a silent and unexpected behavior and errors if not handled carefully.
This package is made to help 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() {
// when there is no overflow
//
fmt.Println(safecast.ToInt8(float64(42)))
// Output: 42, nil
fmt.Println(safecast.ToInt8(int64(-1)))
// Output: -1, nil
// when there is an overflow
//
fmt.Println(safecast.ToInt8(float64(20000)))
// Output: 0 conversion issue: 20000 is greater than 127
fmt.Println(safecast.ToUint8(int64(-1)))
//
…