safecast
Safe Numeric Type Cast Library for Go
English | 简体中文
Safe numeric type cast library. suppoer all integral and floating types, except uintptr.
This library depends on go generics, which is introduced in 1.18+.
Usage:
val, ok := To[type](value)
ok == false
indicates overflow occured. but whatever,val
is always equals to the result of the type cast (type(value)
) expression。
safecast
import "github.com/chen3feng/safecast"
Package safecast provide a safe way to cast a numeric value from type A to type B, with overflow and underflow check.
Index
func To
func To[ToType numericType, FromType numericType](value FromType) (result ToType, ok bool)
To converts a numeric value from the FromType to the specified ToType type safely. result will always be same as the usual type cast (type(value)), but ok is false when overflow or underflow occured.
Example (Float Overflow)
package main
import (
"fmt"
"github.com/chen3feng/safecast"
"math"
)
func main() {
n, ok := safecast.To[float32](math.MaxFloat32 * 2)
fmt.Print(n, ok)
}
Output
+Inf false
Example (Int No Overflow)
package main
import (
"fmt"
"github.com/chen3feng/safecast"
)
func main() {
b, ok := safecast.To[byte](255)
fmt.Print(b, ok)
}
Output
255 true
Example (Int Overflow)
package main
import (
"fmt"
"github.com/chen3feng/safecast"
)
func main() {
b, ok := safecast.To[byte](256)
fmt.Print(b, ok)
}
Output
0 false
Example (Value In Range)
package main
import (
"fmt"
"github.com/chen3feng/safecast"
)
func main() {
n, ok := safecast.To[uint](1)
fmt.Print(n, ok)
}
Output
1 true
Example (Value Out Of Range)
package main
import (
"fmt"
"github.com/chen3feng/safecast"
)
func main() {
n, ok := safecast.To[uint32](-1)
fmt.Print(n, ok)
}
Output
4294967295 false
Generated by gomarkdoc