safeconv

package
v0.0.0-...-ffc4fba Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: Apache-2.0, Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package safeconv provides safe type conversion functions. Must* variants panic on overflow, Safe* variants clamp, To* variants extract typed values.

Index

Constants

View Source
const MaxInt = int(^uint(0) >> 1)

MaxInt is the maximum value for int type (platform-dependent).

View Source
const MaxInt64 = int64(math.MaxInt64)

MaxInt64 is the maximum value for int64 type.

View Source
const MaxUint32 = uint32(math.MaxUint32)

MaxUint32 is the maximum value for uint32 type.

Variables

This section is empty.

Functions

func Extract

func Extract[T any](v any) (T, bool)

Extract type-asserts v (type any) to T. If the direct assertion fails, it attempts numeric coercion via reflect for numeric source and target types. Returns (zero, false) for nil, non-numeric coercion, or type mismatch.

func MustConvert

func MustConvert[From, To Integer](v From) To

MustConvert converts v from From to To, panicking on overflow or sign loss.

func MustIntToUint

func MustIntToUint(v int) uint

MustIntToUint converts int to uint, panics if negative. Prefer MustConvert[int, uint] for new code.

func MustIntToUint32

func MustIntToUint32(v int) uint32

MustIntToUint32 converts int to uint32, panics on bounds violation. Prefer MustConvert[int, uint32] for new code.

func MustUintToInt

func MustUintToInt(v uint) int

MustUintToInt converts uint to int, panics on overflow. Prefer MustConvert[uint, int] for new code.

func SafeConvert

func SafeConvert[From, To Integer](v From) To

SafeConvert converts v from From to To, clamping to the target type's range on overflow.

func SafeInt

func SafeInt(v uint64) int

SafeInt converts uint64 to int, clamping on overflow. Prefer SafeConvert[uint64, int] for new code.

func SafeInt64

func SafeInt64(v uint64) int64

SafeInt64 converts uint64 to int64, clamping on overflow. Prefer SafeConvert[uint64, int64] for new code.

func ToFloat64

func ToFloat64(value any) (float64, bool)

ToFloat64 extracts a float64 from an any value via numeric coercion. Returns (0, false) for non-numeric types.

func ToInt

func ToInt(value any) (int, bool)

ToInt extracts an int from an any value via numeric coercion. Returns (0, false) for non-numeric types.

Types

type Integer

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

Integer constrains types to built-in integer types.

Jump to

Keyboard shortcuts

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