reflects

package
v0.6.15 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2024 License: MIT Imports: 12 Imported by: 12

README

Reflects

reflects Provide extends reflect util functions.

  • some features

Install

go get github.com/gookit/goutil/reflects

Go docs

Usage

import "github.com/gookit/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 added in v0.5.10

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

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

func Call added in v0.6.13

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 added in v0.6.13

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 added in v0.6.13

func CanBeNil(typ reflect.Type) bool

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

func ConvSlice added in v0.6.2

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 added in v0.6.13

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 added in v0.6.13

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

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

func EachMap added in v0.6.8

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

EachMap process any map data

func EachStrAnyMap added in v0.6.8

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 added in v0.5.12

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 added in v0.6.13

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 added in v0.5.6

func HasChild(v reflect.Value) bool

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

func Indirect added in v0.5.12

func Indirect(v reflect.Value) reflect.Value

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

func IsAnyInt added in v0.6.8

func IsAnyInt(k reflect.Kind) bool

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

func IsArrayOrSlice added in v0.6.2

func IsArrayOrSlice(k reflect.Kind) bool

IsArrayOrSlice check. eg: array, slice

func IsEmpty added in v0.5.6

func IsEmpty(v reflect.Value) bool

IsEmpty reflect value check

func IsEmptyReal added in v0.6.11

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 added in v0.5.6

func IsEqual(src, dst any) bool

IsEqual determines if two objects are considered equal.

TIP: cannot compare function type

func IsFunc added in v0.5.6

func IsFunc(val any) bool

IsFunc value

func IsIntLike added in v0.6.13

func IsIntLike(k reflect.Kind) bool

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

func IsIntx added in v0.6.8

func IsIntx(k reflect.Kind) bool

IsIntx check is intX type

func IsNil added in v0.5.6

func IsNil(v reflect.Value) bool

IsNil reflect value

func IsSimpleKind added in v0.6.9

func IsSimpleKind(k reflect.Kind) bool

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

func IsUintX added in v0.6.8

func IsUintX(k reflect.Kind) bool

IsUintX check is uintX type

func Len added in v0.5.6

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 added in v0.6.12

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 added in v0.6.13

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 added in v0.6.13

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 added in v0.6.9

func SetRValue(rv, val reflect.Value)

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

func SetUnexportedValue added in v0.6.9

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 added in v0.5.11

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

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

func SliceElemKind added in v0.6.9

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 added in v0.5.8

func SliceSubKind(typ reflect.Type) reflect.Kind

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

func String added in v0.5.12

func String(rv reflect.Value) string

String convert

func ToBaseVal added in v0.6.13

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 added in v0.5.12

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

ToString convert

func TypeElem added in v0.6.12

func TypeElem(t reflect.Type) reflect.Type

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

func TypeReal added in v0.6.12

func TypeReal(t reflect.Type) reflect.Type

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

func UnexportedValue added in v0.6.9

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 added in v0.6.13

func UnwrapAny(v reflect.Value) reflect.Value

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

func ValToString added in v0.5.12

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

ValToString convert handle

func ValueByKind added in v0.5.10

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

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

func ValueByType added in v0.5.11

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 added in v0.5.6

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 added in v0.6.13

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 added in v0.5.12

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

FlatFunc custom collect handle func

type FuncX added in v0.6.13

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 added in v0.6.13

func NewFunc(fn any) *FuncX

NewFunc instance. param fn support func and reflect.Value

func (*FuncX) Call added in v0.6.13

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 added in v0.6.13

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 added in v0.6.13

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

CallRV call the function with given reflect.Value arguments.

func (*FuncX) NumIn added in v0.6.13

func (f *FuncX) NumIn() int

NumIn get the number of func input args

func (*FuncX) NumOut added in v0.6.13

func (f *FuncX) NumOut() int

NumOut get the number of func output args

func (*FuncX) String added in v0.6.13

func (f *FuncX) String() string

String of func

func (*FuncX) WithEnhanceConv added in v0.6.13

func (f *FuncX) WithEnhanceConv() *FuncX

WithEnhanceConv set enhance convert

func (*FuncX) WithTypeChecker added in v0.6.13

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 added in v0.6.13

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 added in v0.5.6

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 added in v0.5.6

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 added in v0.5.6

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 added in v0.5.6

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