gocast

package module
v2.0.6 Latest Latest
Warning

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

Go to latest
Published: May 17, 2023 License: MIT Imports: 11 Imported by: 0

README

GoCast

GoDoc Build Status Go Report Card Coverage Status

Easily convert basic types into any other basic types.

What is GoCast?

Cast is a library to convert between different GO types in a consistent and easy way.

The library provides a set of methods with the universal casting of types.

The new version still support old conversion functions like ToString, ToInt, ToMap and etc. The new version uses insted just the name od the type Str, Number[type], Map[K,V] and etc. Also was added new functions which returns the error apearing during type casting, all such functions starts from word Try{Name}. Like TryStr, TryNumber[type], TryMap[K,V], TryCast[type] and etc.

Usage example

import "github.com/demdxx/gocast/v2"

// Example string casting:
gocast.Str("strasstr")           // "strasstr"
gocast.Str(8)                    // "8"
gocast.Str(8.31)                 // "8.31"
gocast.Str([]byte("one time"))   // "one time"
gocast.Str(nil)                  // ""

var foo any = "one more time"
gocast.Str(foo)                  // "one more time"

// Example number casting:
gocast.Number[int](8)            // 8
gocast.Number[int](8.31)         // 8
gocast.Number[int]("8")          // 8
gocast.Number[int](true)         // 1
gocast.Number[int](false)        // 0

var eight any = 8
gocast.Number[int](eight)        // 8
gocast.Cast[int](eight)          // 8
gocast.Number[int](nil)          // 0

// Number converts only into numeric values (simpler and faster then Cast)
gocast.Number[float32]("2.12")   // 2.12

// Cast converts any type to any other type
gocast.Cast[float64]("2.")       // 2.0

val, err := gocast.TryCast[int]("123.2") // 123, <nil>
func sumAll(vals ...any) int {
  var result int = 0
  for _, v := range vals {
    result += gocast.Number[int](v)
  }
  return result
}
Structures
type User struct {
  ID    uint64
  Email string
}

var user User

// Set structure values
err := gocast.SetStructFieldValue(&user, "ID", uint64(19))
err := gocast.SetStructFieldValue(&user, "Email", "iamawesome@mail.com")

id, err := gocast.StructFieldValue(user, "ID")
email, err := gocast.StructFieldValue(user, "Email")
fmt.Printf("User: %d - %s", id, email)
// > User: 19 - iamawesome@mail.com

Benchmarks

> go test -benchmem -v -race -bench=.

goos: darwin
goarch: amd64
pkg: github.com/demdxx/gocast/v2
cpu: VirtualApple @ 2.50GHz
BenchmarkApproachTest
BenchmarkApproachTest/bench1
BenchmarkApproachTest/bench1-8    307263              3611 ns/op          0 B/op           0 allocs/op
BenchmarkApproachTest/bench2
BenchmarkApproachTest/bench2-8    337455              3546 ns/op          0 B/op           0 allocs/op
BenchmarkBool
BenchmarkBool-8                 16757396                75.54 ns/op       0 B/op           0 allocs/op
BenchmarkToBoolByReflect
BenchmarkToBoolByReflect-8      10259976               121.2 ns/op        0 B/op           0 allocs/op
BenchmarkToFloat
BenchmarkToFloat-8               7107516               169.0 ns/op        2 B/op           0 allocs/op
BenchmarkToInt
BenchmarkToInt-8                 7212882               168.5 ns/op        2 B/op           0 allocs/op
BenchmarkToUint
BenchmarkToUint-8                7202331               166.8 ns/op        2 B/op           0 allocs/op
BenchmarkToStringByReflect
BenchmarkToStringByReflect-8      970101              1251 ns/op          6 B/op           0 allocs/op
BenchmarkToString
BenchmarkToString-8               995446              1166 ns/op          6 B/op           0 allocs/op
BenchmarkGetSetFieldValue
BenchmarkGetSetFieldValue/set
BenchmarkGetSetFieldValue/set-8                  1468659               821.3 ns/op        32 B/op          2 allocs/op
BenchmarkGetSetFieldValue/get
BenchmarkGetSetFieldValue/get-8                  1407585               851.8 ns/op        48 B/op          3 allocs/op
BenchmarkParseTime
BenchmarkParseTime-8                              504934              2258 ns/op         464 B/op          5 allocs/op
BenchmarkIsEmpty
BenchmarkIsEmpty-8                              26776375                54.08 ns/op        0 B/op          0 allocs/op
PASS
ok      github.com/demdxx/gocast/v2     18.977s

License

The MIT License (MIT)

Copyright (c) 2014 Dmitry Ponomarev demdxx@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidParams                 = errors.New("invalid params")
	ErrUnsupportedType               = errors.New("unsupported destination type")
	ErrUnsupportedSourceType         = errors.New("unsupported source type")
	ErrUnsettableValue               = errors.New("can't set value")
	ErrUnsupportedNumericType        = errors.New("unsupported numeric type")
	ErrStructFieldNameUndefined      = errors.New("struct field name undefined")
	ErrStructFieldValueCantBeChanged = errors.New("struct field value cant be changed")
)

Error list...

Functions

func Bool

func Bool(v any) bool

Bool from any other basic types

func Cast

func Cast[R any, T any](v T, tags ...string) R

Cast source type into the target type

func CastContext

func CastContext[R any, T any](ctx context.Context, v T, tags ...string) R

CastContext source type into the target type

func CastRecursive

func CastRecursive[R any, T any](v T, tags ...string) R

CastRecursive source type into the target type

func CastRecursiveContext

func CastRecursiveContext[R any, T any](ctx context.Context, v T, tags ...string) R

CastRecursiveContext source type into the target type

func Float

func Float(v any) float64

Float from any other basic type, float64 by default

func Float32

func Float32(v any) float32

Float32 from any other basic type

func Float64

func Float64(v any) float64

Float64 from any other basic type

func Int

func Int(v any) int

Int from any other basic type

func Int16

func Int16(v any) int16

Int16 from any other basic type

func Int32

func Int32(v any) int32

Int32 from any other basic type

func Int64

func Int64(v any) int64

Int64 from any other basic type

func Int8

func Int8(v any) int8

Int8 from any other basic type

func IsEmpty

func IsEmpty[T any](v T) bool

IsEmpty checks value for empty state

func IsEmptyByReflection

func IsEmptyByReflection(v reflect.Value) bool

IsEmptyByReflection value

func Len

func Len[T any](val T) int

Len returns size of slice, array or map

func Map

func Map[K comparable, V any](src any, tags ...string) map[K]V

Map creates map from source or returns nil

func MapContext

func MapContext[K comparable, V any](ctx context.Context, src any, tags ...string) map[K]V

MapContext creates map from source or returns nil

func MapRecursive

func MapRecursive[K comparable, V any](src any, tags ...string) map[K]V

MapRecursive creates map from source or returns nil

func MapRecursiveContext

func MapRecursiveContext[K comparable, V any](ctx context.Context, src any, tags ...string) map[K]V

MapRecursiveContext creates map from source or returns nil

func Number

func Number[R Numeric](v any) R

Number converts from types which could be numbers or returns 0

func ParseTime

func ParseTime(tm string) (t time.Time, err error)

ParseTime from string

func ReflectStr

func ReflectStr(v reflect.Value) string

ReflectStr converts reflection value to string

func ReflectStructFieldValue

func ReflectStructFieldValue(st reflect.Value, names ...string) (any, error)

ReflectStructFieldValue returns the value of the struct field

func ReflectToBool

func ReflectToBool(v reflect.Value) bool

ReflectToBool returns boolean from reflection

func ReflectToFloat64

func ReflectToFloat64(v reflect.Value) float64

ReflectToFloat64 returns float64 from reflection

func ReflectToInt64

func ReflectToInt64(v reflect.Value) int64

ReflectToInt64 returns int64 from reflection

func ReflectToString deprecated

func ReflectToString(v reflect.Value) string

ReflectToString converts reflection value to string

Deprecated: Use TryReflectStr instead

func ReflectToType

func ReflectToType(v reflect.Value, t reflect.Type, tags ...string) any

ReflectToType converts reflection valut to reflection type or returns nil

func ReflectToTypeContext

func ReflectToTypeContext(ctx context.Context, v reflect.Value, t reflect.Type, tags ...string) any

ReflectToType converts reflection valut to reflection type or returns nil

func ReflectTryToType

func ReflectTryToType(v reflect.Value, t reflect.Type, recursive bool, tags ...string) (any, error)

ReflectTryToType converts reflection value to reflection type or returns error

func ReflectTryToTypeContext

func ReflectTryToTypeContext(ctx context.Context, v reflect.Value, t reflect.Type, recursive bool, tags ...string) (any, error)

ReflectTryToTypeContext converts reflection value to reflection type or returns error

func SetStructFieldValue

func SetStructFieldValue(ctx context.Context, st any, name string, value any) (err error)

SetStructFieldValue puts value into the struct field

func Slice

func Slice[R any, S any](src []S, tags ...string) []R

Slice converts one type of array to other or resturns nil if not compatible

func SliceContext

func SliceContext[R any, S any](ctx context.Context, src []S, tags ...string) []R

SliceContext converts one type of array to other or resturns nil if not compatible

func Str

func Str(v any) string

Str returns string value from any type

func Struct

func Struct[R any](src any, tags ...string) (R, error)

Struct convert any input type into the target structure

func StructContext

func StructContext[R any](ctx context.Context, src any, tags ...string) (R, error)

StructContext convert any input type into the target structure

func StructFieldTags

func StructFieldTags(st any, tag string) map[string]string

StructFieldTags returns Map with key->tag matching

func StructFieldTagsUnsorted

func StructFieldTagsUnsorted(st any, tag string) ([]string, []string)

StructFieldTagsUnsorted returns field names and tag targets separately

func StructFieldValue

func StructFieldValue(st any, names ...string) (any, error)

StructFieldValue returns the value of the struct field

func StructFields

func StructFields(st any, tag string) []string

StructFields returns the field names from the structure

func To

func To(v, to any, tags ...string) any

TryTo cast any input type into the target

func ToBool deprecated

func ToBool(v any) bool

ToBool from any other basic types

Deprecated: Use Bool(v) instead

func ToFloat deprecated

func ToFloat(v any) float64

ToFloat from any other basic types

Deprecated: Use Number[float64](v) instead

func ToFloat32 deprecated

func ToFloat32(v any) float32

ToFloat32 from any other basic types

Deprecated: Use Number[float32](v) instead

func ToFloat64 deprecated

func ToFloat64(v any) float64

ToFloat64 from any other basic types

Deprecated: Use Number[float64](v) instead

func ToFloat64Slice deprecated

func ToFloat64Slice(v any) []float64

ToFloat64Slice converts any input slice into Float64 type slice

Deprecated: Use Slice[float64](v) instead

func ToInt deprecated

func ToInt(v any) int

ToInt from any other basic types

Deprecated: Use Number[int](v) or Int instead

func ToInt16 deprecated

func ToInt16(v any) int16

ToInt16 from any other basic types

Deprecated: Use Number[int16](v) or Int16 instead

func ToInt32 deprecated

func ToInt32(v any) int32

ToInt32 from any other basic types

Deprecated: Use Number[int32](v) or Int32 instead

func ToInt64 deprecated

func ToInt64(v any) int64

ToInt64 from any other basic types

Deprecated: Use Number[int64](v) or Int64 instead

func ToIntSlice deprecated

func ToIntSlice(v any) []int

ToIntSlice converts any input slice into Int type slice

Deprecated: Use Slice[int](v) instead

func ToInterfaceSlice deprecated

func ToInterfaceSlice(v any) []any

ToInterfaceSlice converts any input slice into Interface type slice

Deprecated: Use Slice[any](v) instead

func ToMap

func ToMap(dst, src any, recursive bool, tags ...string) error

ToMap cast your Source into the Destination type tag defines the tags name in the structure to map the keys

func ToMapContext

func ToMapContext(ctx context.Context, dst, src any, recursive bool, tags ...string) error

ToMap cast your Source into the Destination type tag defines the tags name in the structure to map the keys

func ToMapFrom

func ToMapFrom(src any, recursive bool, tags ...string) (map[any]any, error)

ToMapFrom any Map/Object type

func ToSiMap deprecated

func ToSiMap(src any, recursive bool, tags ...string) (map[string]any, error)

ToSiMap converts input Map/Object type into the map[string]any

Deprecated: Use TryMapFrom[string, any](...) instead

func ToSlice deprecated

func ToSlice(dst, src any, tags ...string) error

ToSlice converts any input slice into destination type slice

Deprecated: Use Slice[type](v) or TrySlice[type](v) instead

func ToString deprecated

func ToString(v any) string

ToString from any type

Deprecated: Use Str instead

func ToStringMap deprecated

func ToStringMap(src any, recursive bool, tags ...string) (map[string]string, error)

ToStringMap converts input Map/Object type into the map[string]string

Deprecated: Use TryMapFrom[string, string](...) instead

func ToStringSlice deprecated

func ToStringSlice(v any) []string

ToStringSlice converts any input slice into String type slice

Deprecated: Use Slice[string](v) instead

func ToStruct deprecated

func ToStruct(dst, src any, tags ...string) error

ToStruct convert any input type into the target structure

Deprecated: Use TryCopyStruct instead

func ToType

func ToType(v any, t reflect.Type, tags ...string) any

ToType cast any input type into the target reflection

func ToUint deprecated

func ToUint(v any) uint

ToUint from any other basic types

Deprecated: Use Number[uint](v) or Uint instead

func ToUint16 deprecated

func ToUint16(v any) uint16

ToUint32 from any other basic types

Deprecated: Use Number[uint16](v) or Uint16 instead

func ToUint32 deprecated

func ToUint32(v any) uint32

ToUint32 from any other basic types

Deprecated: Use Number[uint32](v) or Uint32 instead

func ToUint64 deprecated

func ToUint64(v any) uint64

ToUint64 from any other basic types

Deprecated: Use Number[uint64](v) or Uint64 instead

func ToUint64ByReflect

func ToUint64ByReflect(v reflect.Value) uint64

ToUint64ByReflect returns uint64 from reflection

func TryAnySliceContext

func TryAnySliceContext(ctx context.Context, dst, src any, tags ...string) error

TryAnySliceContext converts any input slice into destination type slice

func TryCast

func TryCast[R any, T any](v T, tags ...string) (R, error)

TryCast source type into the target type

func TryCastContext

func TryCastContext[R any, T any](ctx context.Context, v T, tags ...string) (R, error)

TryCastContext source type into the target type

func TryCastRecursive

func TryCastRecursive[R any, T any](v T, tags ...string) (R, error)

TryCastRecursive source type into the target type with recursive data converting

func TryCastRecursiveContext

func TryCastRecursiveContext[R any, T any](ctx context.Context, v T, tags ...string) (R, error)

TryCastRecursiveContext source type into the target type with recursive data converting

func TryCastValue

func TryCastValue[R any, T any](v T, recursive bool, tags ...string) (R, error)

TryCastValue source type into the target type

func TryCastValueContext

func TryCastValueContext[R any, T any](ctx context.Context, v T, recursive bool, tags ...string) (R, error)

TryCastValueContext source type into the target type

func TryCopyStruct

func TryCopyStruct(dst, src any, tags ...string) (err error)

TryCopyStruct convert any input type into the target structure

func TryCopyStructContext

func TryCopyStructContext(ctx context.Context, dst, src any, tags ...string) (err error)

TryCopyStructContext convert any input type into the target structure

func TryMap

func TryMap[K comparable, V any](src any, tags ...string) (map[K]V, error)

TryMap creates new map to convert from soruce type

func TryMapContext

func TryMapContext[K comparable, V any](ctx context.Context, src any, tags ...string) (map[K]V, error)

TryMapContext creates new map to convert from soruce type

func TryMapCopy

func TryMapCopy[K comparable, V any](dst map[K]V, src any, recursive bool, tags ...string) error

TryMapCopy converts source into destination or return error

func TryMapCopyContext

func TryMapCopyContext[K comparable, V any](ctx context.Context, dst map[K]V, src any, recursive bool, tags ...string) error

TryMapCopyContext converts source into destination or return error

func TryMapFrom

func TryMapFrom[K comparable, V any](src any, recursive bool, tags ...string) (map[K]V, error)

TryMapFrom source creates new map to convert

func TryMapFromContext

func TryMapFromContext[K comparable, V any](ctx context.Context, src any, recursive bool, tags ...string) (map[K]V, error)

TryMapFrom source creates new map to convert

func TryMapRecursive

func TryMapRecursive[K comparable, V any](src any, tags ...string) (map[K]V, error)

TryMapRecursive creates new map to convert from soruce type with recursive field processing

func TryMapRecursiveContext

func TryMapRecursiveContext[K comparable, V any](ctx context.Context, src any, tags ...string) (map[K]V, error)

TryMapRecursiveContext creates new map to convert from soruce type with recursive field processing

func TryNumber

func TryNumber[R Numeric](v any) (R, error)

TryNumber converts from types which could be numbers

func TryReflectStr

func TryReflectStr(v reflect.Value) (string, error)

TryReflectStr converts reflection value to string

func TryReflectToString deprecated

func TryReflectToString(v reflect.Value) (string, error)

TryReflectToString converts reflection value to string

Deprecated: Use TryReflectStr instead

func TrySlice

func TrySlice[R any, S any](src []S, tags ...string) (res []R, err error)

TrySlice converts one type of array to other or resturns error

func TrySliceContext

func TrySliceContext[R any, S any](ctx context.Context, src []S, tags ...string) (res []R, err error)

TrySliceContext converts one type of array to other or resturns error

func TryStr

func TryStr(v any) (string, error)

TryStr from any type

func TryTo

func TryTo(v, to any, tags ...string) (any, error)

TryTo cast any input type into the target

func TryToContext

func TryToContext(ctx context.Context, v any, to reflect.Type, tags ...string) (any, error)

TryToContext cast any input type into the target

func TryToString deprecated

func TryToString(v any) (string, error)

TryToString returns string value from any type

Deprecated: Use TryStr instead

func TryToType

func TryToType(v any, t reflect.Type, tags ...string) (any, error)

TryToType cast any input type into the target reflection

func TryToTypeContext

func TryToTypeContext(ctx context.Context, v any, t reflect.Type, tags ...string) (any, error)

TryToTypeContext cast any input type into the target reflection

func Uint

func Uint(v any) uint

Uint from any other basic type

func Uint16

func Uint16(v any) uint16

Uint16 from any other basic type

func Uint32

func Uint32(v any) uint32

Uint32 from any other basic type

func Uint64

func Uint64(v any) uint64

Uint64 from any other basic type

func Uint8

func Uint8(v any) uint8

Uint8 from any other basic type

Types

type CastSetter

type CastSetter interface {
	CastSet(ctx context.Context, v any) error
}

CastSetter interface from some type into the specific value

type Numeric

type Numeric interface {
	constraints.Integer | constraints.Float
}

Numeric data type

Jump to

Keyboard shortcuts

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