xreflect

package module
v0.0.0-...-6df0df9 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2023 License: BSD-2-Clause Imports: 5 Imported by: 6

README

xreflect

Go Report Card Coverage Status Static Badge Static Badge

A simple and user-friendly reflection utility library.

The xreflect package aims to provide developers with high-level abstractions over the Go standard reflect library. This library's API is often considered low-level and unintuitive, making simple tasks like setting structure field values more complex than necessary.

The main features supported are:

  • Setting the values of structure fields, supporting nested structure field values by using paths such as A.B.C.

  • Getting the values, types, tags, etc., of structure fields.

  • Traversing all fields of a structure, supporting both select mode and range mode. If a deep traversal method like FieldsDeep is used, it will traverse all nested structures.

  • Function calls and method calls, supporting variadic parameters.

  • Creating new instances, checking interface implementations, and more.

Installation and Docs

Install using go get github.com/morrisxyang/xreflect.

Full documentation is available at https://pkg.go.dev/github.com/morrisxyang/xreflect

Quick Start

Set nested struct field value

person := &Person{
	Name: "John",
	Age:  20,
	Country: Country{
		ID:   0,
		Name: "Perk",
	},
}

_ = SetEmbedField(person, "Country.ID", 1)

// Perk's ID: 1 
fmt.Printf("Perk's ID: %d \n", person.Country.ID)

Find json tag

type Person struct {
	Name string `json:"name" xml:"_name"`
}
p := &Person{}
// json:"name" xml:"_name"
fmt.Println(StructFieldTag(p, "Name"))
// name <nil>
fmt.Println(StructFieldTagValue(p, "Name", "json"))
// _name <nil>
fmt.Println(StructFieldTagValue(p, "Name", "xml"))

Filter instance fields (deep traversal)

type Person struct {
	id   string
	Age  int    `json:"int"`
	Name string `json:"name"`
	Home struct {
		Address string `json:"address"`
	}
}

p := &Person{}
fields, _ := SelectFieldsDeep(p, func(s string, field reflect.StructField, value reflect.Value) bool {
	return field.Tag.Get("json") != ""
})
// key: Age type: int
// key: Name type: string
// key: Home.Address type: string
for k, v := range fields {
	fmt.Printf("key: %s type: %v\n", k, v.Type())
}

Call a function

var addFunc = func(nums ...int) int {
		var sum int
		for _, num := range nums {
			sum += num
		}
		return sum
}

res, _ := CallFunc(addFunc, 1, 2, 3)

// 6
fmt.Println(res[0].Interface())

Core Methods

FieldX
SetX
StrcutFieldX
FuncX
Others

FAQ

What is the difference between Field and StructField?

Field returns reflect.Value, while StructField returns reflect.StructField.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnonymousStructFields

func AnonymousStructFields(obj interface{}) ([]reflect.StructField, error)

AnonymousStructFields returns the slice of reflect.StructField of all anonymous fields in obj. The obj can either be a structure or pointer to structure.

func CallFunc

func CallFunc(fn interface{}, args ...interface{}) ([]reflect.Value, error)

CallFunc invokes a function using reflection and returns the result. It supports variadic arguments and uses the Call method of reflect.Value underneath. Variadic arguments need to be flattened, otherwise should use CallFuncSlice. There is no need to parse errors from the returned []reflect.Value. If the called function's last return value is an error, it will be extracted and returned as the last return value of CallFunc.

func CallFuncSlice

func CallFuncSlice(fn interface{}, args ...interface{}) ([]reflect.Value, error)

CallFuncSlice has the same functionality as CallFunc, it must have variadic parameters, but it uses the CallSlice method of reflect.Value under the hood. CallSlice calls the variadic function v with the input arguments in, assigning the slice in[len(in)-1] to v's final variadic argument. For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).

func CallMethod

func CallMethod(obj interface{}, method string, params ...interface{}) ([]reflect.Value, error)

CallMethod calls the method `method` of the `obj` object and returns the result, supporting variadic parameters. The `obj` object must be a struct or a struct pointer. It internally uses CallFunc, see CallFunc for more details.

func CallMethodSlice

func CallMethodSlice(obj interface{}, method string, params ...interface{}) ([]reflect.Value, error)

CallMethodSlice has the same functionality as CallMethod, and it uses CallFuncSlice as its underlying implementation. For more details, refer to the CallFuncSlice documentation.

func EmbedField

func EmbedField(obj interface{}, fieldPath string) (reflect.Value, error)

EmbedField returns the reflect.Value of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedFieldKind

func EmbedFieldKind(obj interface{}, fieldPath string) (reflect.Kind, error)

EmbedFieldKind returns the reflect.Kind of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedFieldType

func EmbedFieldType(obj interface{}, fieldPath string) (reflect.Type, error)

EmbedFieldType returns the reflect.Type of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedFieldTypeStr

func EmbedFieldTypeStr(obj interface{}, fieldPath string) (string, error)

EmbedFieldTypeStr returns the string of the reflect.Type of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedFieldValue

func EmbedFieldValue(obj interface{}, fieldPath string) (interface{}, error)

EmbedFieldValue returns the actual value of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedStructField

func EmbedStructField(obj interface{}, fieldPath string) (reflect.StructField, error)

EmbedStructField returns the reflect.Value of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedStructFieldKind

func EmbedStructFieldKind(obj interface{}, fieldPath string) (reflect.Kind, error)

EmbedStructFieldKind returns the reflect.Kind of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedStructFieldType

func EmbedStructFieldType(obj interface{}, fieldPath string) (reflect.Type, error)

EmbedStructFieldType returns the reflect.Type of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func EmbedStructFieldTypeStr

func EmbedStructFieldTypeStr(obj interface{}, fieldPath string) (string, error)

EmbedStructFieldTypeStr returns the string of the reflect.Type of a field in the nested structure of obj based on the specified fieldPath. The obj can either be a structure or a pointer to a structure.

func Field

func Field(obj interface{}, fieldName string) (reflect.Value, error)

Field returns the reflect.Value of the provided obj field. The obj can either be a structure or pointer to structure.

func FieldKind

func FieldKind(obj interface{}, fieldName string) (reflect.Kind, error)

FieldKind returns the reflect.Kind of the provided obj field. The obj can either be a structure or pointer to structure.

func FieldType

func FieldType(obj interface{}, fieldName string) (reflect.Type, error)

FieldType returns the reflect.Type of the provided obj field. The obj can either be a structure or pointer to structure.

func FieldTypeStr

func FieldTypeStr(obj interface{}, fieldName string) (string, error)

FieldTypeStr returns the string of reflect.Type of the provided obj field. The obj can either be a structure or pointer to structure.

func FieldValue

func FieldValue(obj interface{}, fieldName string) (interface{}, error)

FieldValue returns the actual value of the provided obj field. The obj can either be a structure or pointer to structure.

func Fields

func Fields(obj interface{}) (map[string]reflect.Value, error)

Fields returns a map of reflect.Value containing all the fields of the obj, with the field names as keys. The obj can either be a structure or a pointer to a structure.

func FieldsDeep

func FieldsDeep(obj interface{}) (map[string]reflect.Value, error)

FieldsDeep traverses the obj deeply, including all nested structures, and returns all fields as reflect.Value in the form of a map, where the key is the path of the field. The obj can either be a structure or pointer to structure.

func GetPkgPath

func GetPkgPath(obj interface{}) string

GetPkgPath returns the package path of obj.

func HasStructField

func HasStructField(obj interface{}, fieldName string) (bool, error)

HasStructField checks if the provided obj struct has field named fieldName. The obj can either be a structure or pointer to structure.

func Implements

func Implements(obj interface{}, in interface{}) bool

Implements returns whether obj implements the given interface in.

func NewInstance

func NewInstance(obj interface{}) interface{}

NewInstance returns a new instance of the same type as the input value. The returned value will contain the zero value of the type. If obj type is a slice, chan, etc. , it will create an instance with the same capacity.

func RangeFields

func RangeFields(obj interface{}, f func(string, reflect.StructField, reflect.Value) bool) error

RangeFields iterates over all fields of obj and calls function f on each field. If function f returns false, the iteration stops. The obj can either be a structure or pointer to structure.

func RangeFieldsDeep

func RangeFieldsDeep(obj interface{}, f func(string, reflect.StructField, reflect.Value) bool) error

RangeFieldsDeep performs a deep traversal of obj and its nested structures, and calls function f on each field. If the function f returns false, the iteration stops. The obj can either be a structure or pointer to structure.

func RangeStructFields

func RangeStructFields(obj interface{}, f func(int, reflect.StructField) bool) error

RangeStructFields iterates over all struct fields of obj and calls function f on each field. If function f returns false, the iteration stops. The obj can either be a structure or pointer to structure.

func SelectFields

func SelectFields(obj interface{}, f func(string, reflect.StructField, reflect.Value) bool) (map[string]reflect.Value,
	error)

SelectFields has the same functionality as Fields, but only the fields for which the function f returns true will be returned. The obj can either be a structure or pointer to structure.

func SelectFieldsDeep

func SelectFieldsDeep(obj interface{},
	f func(string, reflect.StructField, reflect.Value) bool) (map[string]reflect.Value,
	error)

SelectFieldsDeep has the same functionality as FieldsDeep, but only the fields for which the function f returns true will be returned. The obj can either be a structure or pointer to structure.

func SelectStructFields

func SelectStructFields(obj interface{}, f func(int, reflect.StructField) bool) ([]reflect.StructField, error)

SelectStructFields has the same functionality as StructFields, but only the fields for which the function f returns true will be returned. The obj can either be a structure or pointer to structure.

func SetEmbedField

func SetEmbedField(obj interface{}, fieldPath string, fieldValue interface{}) error

SetEmbedField sets a nested struct field using fieldPath. The rest of the functionality is the same as SetField. For example, fieldPath can be "FieldA.FieldB.FieldC", where FieldA and FieldB must be structures or pointers to structures. If FieldB does not exist, it will be automatically created. The obj can either be a structure or pointer to structure.

func SetField

func SetField(obj interface{}, fieldName string, fieldValue interface{}) error

SetField sets the fieldName field of the obj object according to the fieldValue parameter. The obj can either be a structure or a pointer to a structure. The type of fieldValue must be compatible with the type of the fieldName field, otherwise it will panic.

func SetPrivateField

func SetPrivateField(obj interface{}, fieldName string, fieldValue interface{}) error

SetPrivateField is similar to SetField, but it allows you to set private fields of an object. The obj can be either a structure or a pointer to a structure.

func StructField

func StructField(obj interface{}, fieldName string) (reflect.StructField, error)

StructField returns the reflect.StructField of the provided obj field. The obj can either be a structure or pointer to structure.

func StructFieldKind

func StructFieldKind(obj interface{}, fieldName string) (reflect.Kind, error)

StructFieldKind returns the reflect.Kind of the provided obj field. The obj can either be a structure or pointer to structure.

func StructFieldTag

func StructFieldTag(obj interface{}, fieldName string) (reflect.StructTag, error)

StructFieldTag returns the reflect.StructTag of the provided obj field. The obj parameter can either be a structure or pointer to structure.

func StructFieldTagValue

func StructFieldTagValue(obj interface{}, fieldName, tagKey string) (string, error)

StructFieldTagValue returns the provided obj field tag value. The obj parameter can either be a structure or pointer to structure.

func StructFieldType

func StructFieldType(obj interface{}, fieldName string) (reflect.Type, error)

StructFieldType returns the reflect.Type of the provided obj field. The obj can either be a structure or pointer to structure.

func StructFieldTypeStr

func StructFieldTypeStr(obj interface{}, fieldName string) (string, error)

StructFieldTypeStr returns the string of reflect.Type of the provided obj field. The obj can either be a structure or pointer to structure.

func StructFields

func StructFields(obj interface{}) ([]reflect.StructField, error)

StructFields returns a slice of reflect.StructField containing all the fields of the obj. The obj can either be a structure or a pointer to a structure.

func StructFieldsFlatten

func StructFieldsFlatten(obj interface{}) ([]reflect.StructField, error)

StructFieldsFlatten returns "flattened" struct fields. Note that StructFieldsFlatten treats fields from anonymous inner structs as normal fields.

func Type

func Type(obj interface{}) reflect.Type

Type returns the reflection type of obj. If obj is a pointer, it will be automatically dereferenced once.

func TypePenetrateElem

func TypePenetrateElem(obj interface{}) reflect.Type

TypePenetrateElem performs the same functionality as Type, but it will parse through all pointers until the final type is reached.

func Value

func Value(obj interface{}) reflect.Value

Value returns the reflection value of obj. If obj is a pointer, it will be automatically dereferenced once.

func ValuePenetrateElem

func ValuePenetrateElem(obj interface{}) reflect.Value

ValuePenetrateElem performs the same functionality as Value, but it will parse through all pointers until the final type is reached.

Types

This section is empty.

Jump to

Keyboard shortcuts

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