safecast

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2024 License: Apache-2.0 Imports: 3 Imported by: 0

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

Examples

Constants

This section is empty.

Variables

View Source
var ErrOutOfRange = errors.New("out of range")

Functions

func Convert

func Convert[NumOut Number, NumIn Number](orig NumIn) (converted NumOut, err error)

func MustConvert

func MustConvert[NumOut Number, NumIn Number](orig NumIn) NumOut

func MustRound

func MustRound[NumOut Number, NumIn Float](orig NumIn) NumOut
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

func MustTruncate[NumOut Number, NumIn Float](orig NumIn) NumOut

func Negative

func Negative[T Number](t T) bool

func Round

func Round[NumOut Number, NumIn Float](orig NumIn) (converted NumOut, err error)

func SameSign

func SameSign[T1, T2 Number](a T1, b T2) bool

func Truncate

func Truncate[NumOut Number, NumIn Float](orig NumIn) (converted NumOut, err error)

Types

type Float

type Float interface {
	~float32 | ~float64
}

type Integer

type Integer interface {
	~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~uintptr
}

type Number

type Number interface {
	Integer | Float
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL