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.Conv[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 Conv[NumOut Integer, NumIn Integer](orig NumIn) (converted NumOut, err error)
- func Convert[NumOut Number, NumIn Number](orig NumIn) (converted NumOut, err error)
- func MustConv[NumOut Integer, NumIn Integer](orig NumIn) NumOut
- 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 Conv ¶ added in v1.1.0
Conv is an integer only and simpler version of Convert without the weird issue with round trip to floating point. Unlike Convert it can be used for identity (same type in and out) even if that's of dubious value.
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. Use Conv instead if both of your types are Integer. Do not use for identity (same type in and out) but in particular this will error for Convert[uint64](uint64(math.MaxUint64)) or Convert[int64](int64(math.MaxInt64)) because it needs to when converting to any float. Note that +Inf will convert correctly (as in error only if going to an integer type) from a float64/float32 and not a ~float (it will error from say ~float32 to float64 while it shouldn't).
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.