Path: blob/main/vendor/github.com/spf13/cast/cast.go
2875 views
// Copyright © 2014 Steve Francia <[email protected]>.1//2// Use of this source code is governed by an MIT-style3// license that can be found in the LICENSE file.45// Package cast provides easy and safe casting in Go.6package cast78import "time"910const errorMsg = "unable to cast %#v of type %T to %T"11const errorMsgWith = "unable to cast %#v of type %T to %T: %w"1213// Basic is a type parameter constraint for functions accepting basic types.14//15// It represents the supported basic types this package can cast to.16type Basic interface {17string | bool | Number | time.Time | time.Duration18}1920// ToE casts any value to a [Basic] type.21func ToE[T Basic](i any) (T, error) {22var t T2324var v any25var err error2627switch any(t).(type) {28case string:29v, err = ToStringE(i)30case bool:31v, err = ToBoolE(i)32case int:33v, err = toNumberE[int](i, parseInt[int])34case int8:35v, err = toNumberE[int8](i, parseInt[int8])36case int16:37v, err = toNumberE[int16](i, parseInt[int16])38case int32:39v, err = toNumberE[int32](i, parseInt[int32])40case int64:41v, err = toNumberE[int64](i, parseInt[int64])42case uint:43v, err = toUnsignedNumberE[uint](i, parseUint[uint])44case uint8:45v, err = toUnsignedNumberE[uint8](i, parseUint[uint8])46case uint16:47v, err = toUnsignedNumberE[uint16](i, parseUint[uint16])48case uint32:49v, err = toUnsignedNumberE[uint32](i, parseUint[uint32])50case uint64:51v, err = toUnsignedNumberE[uint64](i, parseUint[uint64])52case float32:53v, err = toNumberE[float32](i, parseFloat[float32])54case float64:55v, err = toNumberE[float64](i, parseFloat[float64])56case time.Time:57v, err = ToTimeE(i)58case time.Duration:59v, err = ToDurationE(i)60}6162if err != nil {63return t, err64}6566return v.(T), nil67}6869// Must is a helper that wraps a call to a cast function and panics if the error is non-nil.70func Must[T any](i any, err error) T {71if err != nil {72panic(err)73}7475return i.(T)76}7778// To casts any value to a [Basic] type.79func To[T Basic](i any) T {80v, _ := ToE[T](i)8182return v83}848586