reflects

package
v0.0.0-...-f5003fd Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2025 License: MIT Imports: 12 Imported by: 0

README

Reflects

reflects Provide extends reflect util functions.

  • some features

Install

go get github.com/Joaolfc0/goutil/reflects

Go docs

Usage

import "github.com/Joaolfc0/goutil/reflects"

// get struct field value
reflects.GetFieldValue(obj, "Name")

Functions API

Note: doc by run go doc ./reflects

func BaseTypeVal(v reflect.Value) (value any, err error)
func ConvSlice(oldSlRv reflect.Value, newElemTyp reflect.Type) (rv reflect.Value, err error)
func EachMap(mp reflect.Value, fn func(key, val reflect.Value))
func EachStrAnyMap(mp reflect.Value, fn func(key string, val any))
func Elem(v reflect.Value) reflect.Value
func FlatMap(rv reflect.Value, fn FlatFunc)
func HasChild(v reflect.Value) bool
func Indirect(v reflect.Value) reflect.Value
func IsAnyInt(k reflect.Kind) bool
func IsArrayOrSlice(k reflect.Kind) bool
func IsEmpty(v reflect.Value) bool
func IsEmptyValue(v reflect.Value) bool
func IsEqual(src, dst any) bool
func IsFunc(val any) bool
func IsIntx(k reflect.Kind) bool
func IsNil(v reflect.Value) bool
func IsSimpleKind(k reflect.Kind) bool
func IsUintX(k reflect.Kind) bool
func Len(v reflect.Value) int
func SetRValue(rv, val reflect.Value)
func SetUnexportedValue(rv reflect.Value, value any)
func SetValue(rv reflect.Value, val any) error
func SliceElemKind(typ reflect.Type) reflect.Kind
func SliceSubKind(typ reflect.Type) reflect.Kind
func String(rv reflect.Value) string
func ToString(rv reflect.Value) (str string, err error)
func UnexportedValue(rv reflect.Value) any
func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error)
func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error)
func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error)
type BKind uint
    func ToBKind(kind reflect.Kind) BKind
    func ToBaseKind(kind reflect.Kind) BKind
type FlatFunc func(path string, val reflect.Value)
type Type interface{ ... }
    func TypeOf(v any) Type
type Value struct{ ... }
    func ValueOf(v any) Value
    func Wrap(rv reflect.Value) Value

Testings

go test -v ./reflects/...

Test limit by regexp:

go test -v -run ^TestSetByKeys ./reflects/...

Documentation

Overview

Package reflects Provide extends reflect util functions.

Index

Constants

View Source
const (
	// Int for all intX types
	Int = reflect.Int
	// Uint for all uintX types
	Uint = reflect.Uint
	// Float for all floatX types
	Float = reflect.Float32
	// Array for array,slice types
	Array = reflect.Array
	// Complex for all complexX types
	Complex = reflect.Complex64
)

base kinds

Variables

View Source
var IsEmptyValue = IsEmptyReal

IsEmptyValue reflect value check, alias of the IsEmptyReal()

View Source
var IsZero = IsEmpty

IsZero reflect value check, alias of the IsEmpty()

View Source
var OneOrTwoOutChecker = func(typ reflect.Type) error {
	if !good1or2outFunc(typ) {
		return errors.New("func allow with 1 result or 2 results where the second is an error")
	}
	return nil
}

OneOrTwoOutChecker check func type. only allow 1 or 2 return values

Allow func returns:

  • 1 return: (value)
  • 2 return: (value, error)

Functions

func BaseTypeVal

func BaseTypeVal(v reflect.Value) (value any, err error)

BaseTypeVal convert custom type or intX,uintX,floatX to generic base type.

func Call

func Call(fn reflect.Value, args []reflect.Value, opt *CallOpt) ([]reflect.Value, error)

Call returns the result of evaluating the first argument as a function.

  • Will check args and try convert input args to func args type.

from text/template/funcs.go#call

func Call2

func Call2(fn reflect.Value, args []reflect.Value) (reflect.Value, error)

Call2 returns the result of evaluating the first argument as a function. The function must return 1 result, or 2 results, the second of which is an error.

  • Only support func with 1 or 2 return values: (val) OR (val, err)
  • Will check args and try convert input args to func args type.

func CanBeNil

func CanBeNil(typ reflect.Type) bool

CanBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.

func ConvSlice

func ConvSlice(oldSlRv reflect.Value, newElemTyp reflect.Type) (rv reflect.Value, err error)

ConvSlice make new type slice from old slice, will auto convert element type.

TIPs:

Only support kind: string, bool, intX, uintX, floatX

func ConvToKind

func ConvToKind(val any, kind reflect.Kind) (rv reflect.Value, err error)

ConvToKind convert and create reflect.Value by give reflect.Kind

TIPs:

Only support kind: string, bool, intX, uintX, floatX

func ConvToType

func ConvToType(val any, typ reflect.Type) (rv reflect.Value, err error)

ConvToType convert and create reflect.Value by give reflect.Type

func EachMap

func EachMap(mp reflect.Value, fn func(key, val reflect.Value))

EachMap process any map data

func EachStrAnyMap

func EachStrAnyMap(mp reflect.Value, fn func(key string, val any))

EachStrAnyMap process any map data as string key and any value

func Elem

func Elem(v reflect.Value) reflect.Value

Elem returns the value that the interface v contains or that the pointer v points to. otherwise, will return self

func FlatMap

func FlatMap(rv reflect.Value, fn FlatFunc)

FlatMap process tree map to flat key-value map.

Examples:

{"top": {"sub": "value", "sub2": "value2"} }
->
{"top.sub": "value", "top.sub2": "value2" }

func FlatSlice

func FlatSlice(sl reflect.Value, depth int) reflect.Value

FlatSlice flatten multi-level slice to given depth-level slice.

Example:

FlatSlice([]any{ []any{3, 4}, []any{5, 6} }, 1) // Output: []any{3, 4, 5, 6}

always return reflect.Value of []any. note: maybe flatSl.Cap != flatSl.Len

func HasChild

func HasChild(v reflect.Value) bool

HasChild type check. eg: array, slice, map, struct

func Indirect

func Indirect(v reflect.Value) reflect.Value

Indirect like reflect.Indirect(), but can also indirect reflect.Interface. otherwise, will return self

func IsAnyInt

func IsAnyInt(k reflect.Kind) bool

IsAnyInt check is intX or uintX type. alias of the IsIntLike()

func IsArrayOrSlice

func IsArrayOrSlice(k reflect.Kind) bool

IsArrayOrSlice check. eg: array, slice

func IsEmpty

func IsEmpty(v reflect.Value) bool

IsEmpty reflect value check

func IsEmptyReal

func IsEmptyReal(v reflect.Value) bool

IsEmptyReal reflect value check.

Note:

Difference the IsEmpty(), if value is ptr or interface, will check real elem.

From src/pkg/encoding/json/encode.go.

func IsEqual

func IsEqual(src, dst any) bool

IsEqual determines if two objects are considered equal.

TIP: cannot compare function type

func IsFunc

func IsFunc(val any) bool

IsFunc value

func IsIntLike

func IsIntLike(k reflect.Kind) bool

IsIntLike reports whether the type is int-like(intX, uintX).

func IsIntx

func IsIntx(k reflect.Kind) bool

IsIntx check is intX type

func IsNil

func IsNil(v reflect.Value) bool

IsNil reflect value

func IsSimpleKind

func IsSimpleKind(k reflect.Kind) bool

IsSimpleKind kind in: string, bool, intX, uintX, floatX

func IsUintX

func IsUintX(k reflect.Kind) bool

IsUintX check is uintX type

func IsValidPtr

func IsValidPtr(v reflect.Value) bool

IsValidPtr check variable is a valid pointer.

func Len

func Len(v reflect.Value) int

Len get reflect value length. allow: intX, uintX, floatX, string, map, array, chan, slice.

Note: (u)intX use width. float to string then calc len.

func MakeSliceByElem

func MakeSliceByElem(elTyp reflect.Type, len, cap int) reflect.Value

MakeSliceByElem create a new slice by the element type.

- elType: the type of the element. - returns: the new slice.

Usage:

sl := MakeSliceByElem(reflect.TypeOf(1), 10, 20)
sl.Index(0).SetInt(10)

// Or use reflect.AppendSlice() merge two slice
// Or use `for` with `reflect.Append()` add elements

func SafeCall

func SafeCall(fun reflect.Value, args []reflect.Value) (ret []reflect.Value, err error)

SafeCall runs fun.Call(args), and returns the resulting values, or an error. If the call panics, the panic value is returned as an error.

func SafeCall2

func SafeCall2(fun reflect.Value, args []reflect.Value) (val reflect.Value, err error)

SafeCall2 runs fun.Call(args), and returns the resulting value and error, if any. If the call panics, the panic value is returned as an error.

NOTE: Only support func with 1 or 2 return values: (val) OR (val, err)

from text/template/funcs.go#safeCall

func SetRValue

func SetRValue(rv, val reflect.Value)

SetRValue to a `reflect.Value`. will direct set value without convert type.

func SetUnexportedValue

func SetUnexportedValue(rv reflect.Value, value any)

SetUnexportedValue quickly set unexported field value by reflect

NOTE: this method is unsafe, use it carefully. should ensure rv is addressable by field.CanAddr()

func SetValue

func SetValue(rv reflect.Value, val any) error

SetValue to a `reflect.Value`. will auto convert type if needed.

func SliceElemKind

func SliceElemKind(typ reflect.Type) reflect.Kind

SliceElemKind get sub-elem kind of the array, slice, variadic-var.

Usage:

SliceElemKind(reflect.TypeOf([]string{"abc"})) // reflect.String

func SliceSubKind

func SliceSubKind(typ reflect.Type) reflect.Kind

SliceSubKind get sub-elem kind of the array, slice, variadic-var. alias SliceElemKind()

func String

func String(rv reflect.Value) string

String convert

func ToBaseVal

func ToBaseVal(v reflect.Value) (value any, err error)

ToBaseVal convert custom type or intX,uintX,floatX to generic base type.

intX 	    => int64
unitX 	    => uint64
floatX      => float64
string 	    => string

returns int64,string,float or error

func ToString

func ToString(rv reflect.Value) (str string, err error)

ToString convert

func TypeElem

func TypeElem(t reflect.Type) reflect.Type

TypeElem returns the array, slice, chan, map type's element type. otherwise, will return self.

func TypeReal

func TypeReal(t reflect.Type) reflect.Type

TypeReal returns a ptr type's real type. otherwise, will return self.

func UnexportedValue

func UnexportedValue(rv reflect.Value) any

UnexportedValue quickly get unexported value by reflect.Value

NOTE: this method is unsafe, use it carefully. should ensure rv is addressable by field.CanAddr()

refer: https://stackoverflow.com/questions/42664837/how-to-access-unexported-struct-fields

func UnwrapAny

func UnwrapAny(v reflect.Value) reflect.Value

UnwrapAny unwrap reflect.Interface value. otherwise, will return self

func ValToString

func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error)

ValToString convert handle

func ValueByKind

func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error)

ValueByKind convert and create reflect.Value by give reflect.Kind

func ValueByType

func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error)

ValueByType create reflect.Value by give reflect.Type

Types

type BKind

type BKind = reflect.Kind

BKind base data kind type, alias of reflect.Kind

Diff with reflect.Kind:

  • Int contains all intX types
  • Uint contains all uintX types
  • Float contains all floatX types
  • Array for array and slice types
  • Complex contains all complexX types

func ToBKind

func ToBKind(kind reflect.Kind) BKind

ToBKind convert reflect.Kind to base kind

func ToBaseKind

func ToBaseKind(kind reflect.Kind) BKind

ToBaseKind convert reflect.Kind to base kind

type CallOpt

type CallOpt struct {
	// TypeChecker check func type before call func. eg: check return values
	TypeChecker TypeCheckerFn
	// EnhanceConv try to enhance auto convert args to func args type
	// 	- support more type: string, int, uint, float, bool
	EnhanceConv bool
}

CallOpt call options

type FlatFunc

type FlatFunc func(path string, val reflect.Value)

FlatFunc custom collect handle func

type FuncX

type FuncX struct {
	CallOpt
	// Name of func. eg: "MyFunc"
	Name string
	// contains filtered or unexported fields
}

FuncX wrap a go func. represent a function

func NewFunc

func NewFunc(fn any) *FuncX

NewFunc instance. param fn support func and reflect.Value

func (*FuncX) Call

func (f *FuncX) Call(args ...any) ([]any, error)

Call the function with given arguments.

Usage:

func main() {
	fn := func(a, b int) int {
		return a + b
	}

	fx := NewFunc(fn)
	ret, err := fx.Call(1, 2)
	fmt.Println(ret[0], err) // Output: 3 <nil>
}

func (*FuncX) Call2

func (f *FuncX) Call2(args ...any) (any, error)

Call2 returns the result of evaluating the first argument as a function. The function must return 1 result, or 2 results, the second of which is an error.

  • Only support func with 1 or 2 return values: (val) OR (val, err)
  • Will check args and try convert input args to func args type.

func (*FuncX) CallRV

func (f *FuncX) CallRV(args []reflect.Value) ([]reflect.Value, error)

CallRV call the function with given reflect.Value arguments.

func (*FuncX) NumIn

func (f *FuncX) NumIn() int

NumIn get the number of func input args

func (*FuncX) NumOut

func (f *FuncX) NumOut() int

NumOut get the number of func output args

func (*FuncX) String

func (f *FuncX) String() string

String of func

func (*FuncX) WithEnhanceConv

func (f *FuncX) WithEnhanceConv() *FuncX

WithEnhanceConv set enhance convert

func (*FuncX) WithTypeChecker

func (f *FuncX) WithTypeChecker(checker TypeCheckerFn) *FuncX

WithTypeChecker set type checker

type Type

type Type interface {
	reflect.Type
	// BaseKind value
	BaseKind() BKind
	// RealType returns a ptr type's real type. otherwise, will return self.
	RealType() reflect.Type
	// SafeElem returns a type's element type. otherwise, will return self.
	SafeElem() reflect.Type
}

Type struct

func TypeOf

func TypeOf(v any) Type

TypeOf value

type TypeCheckerFn

type TypeCheckerFn func(typ reflect.Type) error

TypeCheckerFn type checker func

type Value

type Value struct {
	reflect.Value
	// contains filtered or unexported fields
}

Value struct

func ValueOf

func ValueOf(v any) Value

ValueOf the give value

func Wrap

func Wrap(rv reflect.Value) Value

Wrap the give value

func (Value) BKind

func (v Value) BKind() BKind

BKind value

func (Value) BaseKind

func (v Value) BaseKind() BKind

BaseKind value

func (Value) Elem

func (v Value) Elem() Value

Elem returns the value that the interface v contains or that the pointer v points to.

TIP: not like reflect.Value.Elem. otherwise, will return self.

func (Value) HasChild

func (v Value) HasChild() bool

HasChild check. eg: array, slice, map, struct

func (Value) Indirect

func (v Value) Indirect() Value

Indirect value. alias of the reflect.Indirect()

func (Value) Int

func (v Value) Int() int64

Int value. if is uintX will convert to int64

func (Value) Type

func (v Value) Type() Type

Type of value.

func (Value) Uint

func (v Value) Uint() uint64

Uint value. if is intX will convert to uint64

Jump to

Keyboard shortcuts

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