Documentation
¶
Overview ¶
Moved to fortio.org/safecast(https://pkg.go.dev/fortio.org/safecast).
Package safecast allows you to safely cast between numeric types in Go and return errors (or panic when using the Must* variants) when the cast would result in a loss of precision, range or sign.
Example ¶
package main
import (
"fmt"
"github.com/ldemailly/go-scratch/safecast"
)
func main() {
var in int16 = 256
// will error out
out, err := safecast.Convert[uint8](in)
fmt.Println(out, err)
// will be fine
out = safecast.MustRound[uint8](255.4)
fmt.Println(out)
// Also fine
out = safecast.MustTruncate[uint8](255.6)
fmt.Println(out)
}
Output: 0 out of range 255 255
Index ¶
- Variables
- func Convert[NumOut Number, NumIn Number](orig NumIn) (converted NumOut, err error)
- func MustConvert[NumOut Number, NumIn Number](orig NumIn) NumOut
- func MustRound[NumOut Number, NumIn Float](orig NumIn) NumOut
- func MustTruncate[NumOut Number, NumIn Float](orig NumIn) NumOut
- func Negative[T Number](t T) bool
- func Round[NumOut Number, NumIn Float](orig NumIn) (converted NumOut, err error)
- func SameSign[T1, T2 Number](a T1, b T2) bool
- func Truncate[NumOut Number, NumIn Float](orig NumIn) (converted NumOut, err error)
- type Float
- type Integer
- type Number
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrOutOfRange = errors.New("out of range")
Functions ¶
func MustConvert ¶
func MustRound ¶
Example ¶
package main
import (
"fmt"
"github.com/ldemailly/go-scratch/safecast"
)
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("panic:", r)
}
}()
out := safecast.MustRound[int8](-128.6)
fmt.Println("not reached", out) // not reached
}
Output: panic: safecast: out of range for -128.6 (float64) to int8
func MustTruncate ¶
Types ¶
Click to show internal directories.
Click to hide internal directories.