Documentation ¶
Overview ¶
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" "fortio.org/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 Round[NumOut Number, NumIn Float](orig NumIn) (converted NumOut, err error)
- 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 ¶
var ErrOutOfRange = errors.New("out of range")
Functions ¶
func Convert ¶
Convert converts a number from one type to another, returning an error if the conversion would result in a loss of precision, range or sign (overflow). In other words if the converted number is not equal to the original number. Do not use for identity (same type in and out) but in particular this will error for Convert[uint64](uint64(math.MaxUint64)) because it needs to when converting to any float.
func MustConvert ¶
Same as Convert but panics if there is an error.
func MustRound ¶
Same as Round but panics if there is an error.
Example ¶
package main import ( "fmt" "fortio.org/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 ¶
Same as Truncate but panics if there is an error.