reflectx

package
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2024 License: BSD-3-Clause Imports: 17 Imported by: 0

Documentation

Overview

Package reflectx provides a collection of helpers for the reflect package in the Go standard library.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnyIsNil

func AnyIsNil(v any) bool

AnyIsNil checks if an interface value is nil. The interface itself could be nil, or the value pointed to by the interface could be nil. This safely checks both.

func CloneToType

func CloneToType(typ reflect.Type, val any) reflect.Value

CloneToType creates a new pointer to the given type and uses SetRobust to copy an existing value (of potentially another type) to it.

func CopyMapRobust

func CopyMapRobust(to, from any) error

CopyMapRobust robustly copies maps.

func CopySliceRobust

func CopySliceRobust(to, from any) error

CopySliceRobust robustly copies slices.

func FormatDefault

func FormatDefault(def string) string

FormatDefault converts the given `default:` struct tag string into a format suitable for being used as a value in SetRobust. If it returns "", the default value should not be used.

func FriendlyTypeName

func FriendlyTypeName(typ reflect.Type) string

FriendlyTypeName returns a user-friendly version of the name of the given type. It transforms it into sentence case, excludes the package, and converts various builtin types into more friendly forms (eg: "int" to "Number").

func KindIsBasic

func KindIsBasic(vk reflect.Kind) bool

KindIsBasic returns whether the given reflect.Kind is a basic, elemental type such as Int, Float, etc.

func LongTypeName

func LongTypeName(typ reflect.Type) string

LongTypeName returns the long, full package-path qualified type name. This is guaranteed to be unique and used for internal storage of several maps to avoid any conflicts. It is also very quick to compute.

func MapAdd

func MapAdd(mv any)

MapAdd adds a new blank entry to the map.

func MapDelete

func MapDelete(mv any, key reflect.Value)

MapDelete deletes the given key from the given map.

func MapDeleteAll

func MapDeleteAll(mv any)

MapDeleteAll deletes everything from the given map.

func MapKeyType

func MapKeyType(mp any) reflect.Type

MapKeyType returns the type of the key for the given map (which can be a pointer to a map or a direct map) -- just Key() of map type, but using this function makes it more explicit what is going on.

func MapSort

func MapSort(mp any, byKey, ascending bool) []reflect.Value

MapSort sorts the keys of the map either by key or by value, and returns those keys as a slice of [reflect.Value]s.

func MapValueSort

func MapValueSort(mpvnp reflect.Value, keys []reflect.Value, ascending bool) error

MapValueSort sorts the keys of the given map by their values.

func MapValueType

func MapValueType(mp any) reflect.Type

MapValueType returns the type of the value for the given map (which can be a pointer to a map or a direct map) -- just Elem() of map type, but using this function makes it more explicit what is going on.

func NonDefaultFields

func NonDefaultFields(v any) map[string]any

NonDefaultFields returns a map representing all of the fields of the given struct (or pointer to a struct) that have values different than their default values as specified by the `default:` struct tag. The resulting map is then typically saved using something like JSON or TOML. If a value has no default value, it checks whether its value is non-zero. If a field has a `save:"-"` tag, it wil not be included in the resulting map.

func NonPointerType

func NonPointerType(typ reflect.Type) reflect.Type

NonPointerType returns a non-pointer version of the given type.

func NonPointerValue

func NonPointerValue(v reflect.Value) reflect.Value

NonPointerValue returns a non-pointer version of the given value.

func NumAllFields

func NumAllFields(typ reflect.Type) int

NumAllFields returns the number of elemental fields in the given struct type.

func NumMapStructElements

func NumMapStructElements(mp any) int

NumMapStructElements returns the number of elemental fields in the given map / struct, using WalkMapStructElements.

func OnePointerType

func OnePointerType(typ reflect.Type) reflect.Type

OnePointerType returns a type that is exactly one pointer away from a non-pointer type.

func OnePointerUnderlyingValue

func OnePointerUnderlyingValue(v reflect.Value) reflect.Value

OnePointerUnderlyingValue returns a value that is exactly one pointer away from a non-pointer value. It also goes through any interfaces to find the actual underlying value.

func OnePointerValue

func OnePointerValue(v reflect.Value) reflect.Value

OnePointerValue returns a value that is exactly one pointer away from a non-pointer value.

func PointerType

func PointerType(typ reflect.Type) reflect.Type

PointerType returns the pointer version of the given type if it is not already a pointer type.

func PointerValue

func PointerValue(v reflect.Value) reflect.Value

PointerValue returns a pointer to the given value if it is not already a pointer.

func SetFromDefaultTag

func SetFromDefaultTag(v reflect.Value, def string) error

SetFromDefaultTag sets the given value from the given default tag.

func SetFromDefaultTags

func SetFromDefaultTags(obj any) error

SetFromDefaultTags sets the values of fields in the given struct based on `default:` default value struct field tags.

func SetMapRobust

func SetMapRobust(mp, ky, val reflect.Value) bool

SetMapRobust robustly sets a map value using reflect.Value representations of the map, key, and value elements, ensuring that the proper types are used for the key and value elements using sensible conversions.

func SetRobust

func SetRobust(to, from any) error

SetRobust robustly sets the 'to' value from the 'from' value. The 'to' value must be a pointer. It copies slices and maps robustly, and it can set a struct, slice, or map from a JSON-formatted string value. It also handles many other cases, so it is unlikely to fail.

Note that maps are not reset prior to setting, whereas slices are set to be fully equivalent to the source slice.

func ShortTypeName

func ShortTypeName(typ reflect.Type) string

ShortTypeName returns the short version of a package-qualified type name which just has the last element of the path. This is what is used in standard Go programming, and is is used for the key to lookup reflect.Type names -- i.e., this is what you should save in a JSON file. The potential naming conflict is worth the brevity, and typically a given file will only contain mutually-compatible, non-conflicting types. This is cached in ShortNames because the path.Base computation is apparently a bit slow.

func SliceDeleteAt

func SliceDeleteAt(sl any, idx int)

SliceDeleteAt deletes the element at the given index in the given slice.

func SliceElementType

func SliceElementType(sl any) reflect.Type

SliceElementType returns the type of the elements of the given slice (which can be a pointer to a slice or a direct slice); just reflect.Type.Elem of slice type, but using this function bypasses any pointer issues and makes it more explicit what is going on.

func SliceElementValue

func SliceElementValue(sl any) reflect.Value

SliceElementValue returns a new reflect.Value of the SliceElementType.

func SliceNewAt

func SliceNewAt(sl any, idx int)

SliceNewAt inserts a new blank element at the given index in the given slice. -1 means the end.

func SliceSort

func SliceSort(sl any, ascending bool) error

SliceSort sorts a slice of basic values (see StructSliceSort for sorting a slice-of-struct using a specific field), using float, int, string, and time.Time conversions.

func StringJSON

func StringJSON(v any) string

StringJSON returns a JSON string representation of the given value for printing/debugging.

func StructSliceSort

func StructSliceSort(structSlice any, fieldIndex []int, ascending bool) error

StructSliceSort sorts the given slice of structs according to the given field indexes and sort direction, using float, int, string, and time.Time conversions. It will panic if the field indexes are invalid.

func StructTags

func StructTags(tags reflect.StructTag) map[string]string

StructTags returns a map[string]string of the tag string from a reflect.StructTag value.

func ToBool

func ToBool(v any) (bool, error)

ToBool robustly converts to a bool any basic elemental type (including pointers to such) using a big type switch organized for greatest efficiency. It tries the bools.Booler interface if not a bool type. It falls back on reflection when all else fails.

func ToFloat

func ToFloat(v any) (float64, error)

ToFloat robustly converts to a float64 any basic elemental type (including pointers to such) using a big type switch organized for greatest efficiency, only falling back on reflection when all else fails.

func ToFloat32

func ToFloat32(v any) (float32, error)

ToFloat32 robustly converts to a float32 any basic elemental type (including pointers to such) using a big type switch organized for greatest efficiency, only falling back on reflection when all else fails.

func ToInt

func ToInt(v any) (int64, error)

ToInt robustly converts to an int64 any basic elemental type (including pointers to such) using a big type switch organized for greatest efficiency, only falling back on reflection when all else fails.

func ToString

func ToString(v any) string

ToString robustly converts anything to a String using a big type switch organized for greatest efficiency. First checks for string or []byte and returns that immediately, then checks for the Stringer interface as the preferred conversion (e.g., for enums), and then falls back on strconv calls for numeric types. If everything else fails, it uses fmt.Sprintf("%v") which always works, so there is no need for an error return value. It returns "nil" for any nil pointers, and byte is converted as string(byte), not the decimal representation.

func ToStringPrec

func ToStringPrec(v any, prec int) string

ToStringPrec robustly converts anything to a String using given precision for converting floating values; using a value like 6 truncates the nuisance random imprecision of actual floating point values due to the fact that they are represented with binary bits. Otherwise is identical to ToString for any other cases.

func ValueSliceSort

func ValueSliceSort(sl []reflect.Value, ascending bool) error

ValueSliceSort sorts a slice of [reflect.Value]s using basic types where possible.

func WalkMapElements

func WalkMapElements(mp any, fun func(mp any, typ reflect.Type, key, val reflect.Value) bool) bool

WalkMapElements calls a function on all the "basic" elements of the given map; it iterates over maps within maps (but not structs and slices within maps).

func WalkMapStructElements

func WalkMapStructElements(mp any, fun func(mp any, typ reflect.Type, val reflect.Value) bool) bool

WalkMapStructElements calls a function on all the "basic" elements of the given map or struct; it iterates over maps within maps and fields within structs.

func WalkTypeAllFields

func WalkTypeAllFields(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool

WalkTypeAllFields calls a function on all the fields of a given struct type, including those on *any* fields of struct fields that this struct has; if fun returns false then iteration stops; overall return value is false if iteration was stopped or there was an error (logged), true otherwise.

func WalkTypeFlatFields

func WalkTypeFlatFields(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool

WalkTypeFlatFields calls a function on all the primary fields of a given struct type, including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField, effectively flattening the reflect field list; if fun returns false then iteration stops; overall return value is false if iteration was stopped or there was an error (logged), true otherwise.

func WalkTypeFlatFieldsIf

func WalkTypeFlatFieldsIf(typ reflect.Type, ifFun, fun func(typ reflect.Type, field reflect.StructField) bool) bool

WalkTypeFlatFieldsIf calls a function on all the primary fields of a given struct type, including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField, effectively flattening the reflect field list; if fun returns false then iteration stops; overall return value is false if iteration was stopped or there was an error (logged), true otherwise. If the given ifFun is non-nil, it is called on every embedded struct field to determine whether the fields of that embedded field should be handled (a return value of true indicates to continue down and a value of false indicates to not).

func WalkValueFlatFields

func WalkValueFlatFields(stru any, fun func(str any, typ reflect.Type, field reflect.StructField, fieldVal reflect.Value) bool) bool

WalkValueFlatFields calls a function on all the primary fields of a given struct value (must pass a pointer to the struct) including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField, which effectively flattens the reflect field list.

func WalkValueFlatFieldsIf

func WalkValueFlatFieldsIf(stru any, ifFun, fun func(str any, typ reflect.Type, field reflect.StructField, fieldVal reflect.Value) bool) bool

WalkValueFlatFieldsIf calls a function on all the primary fields of a given struct value (must pass a pointer to the struct) including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField, which effectively flattens the reflect field list. If the given ifFun is non-nil, it is called on every embedded struct field to determine whether the fields of that embedded field should be handled (a return value of true indicates to continue down and a value of false indicates to not).

Types

type Inter

type Inter interface {
	// Int returns the value as an int64.
	Int() int64
}

Inter is an interface that requires a method returning the value as an int64. It is used in sorting and implemented by cogentcore.org/core/fileinfo.FileTime.

type SetAnyer

type SetAnyer interface {
	SetAny(v any) error
}

SetAnyer represents a type that can be set from any value. It is checked in SetRobust.

type SetStringer

type SetStringer interface {
	SetString(s string) error
}

SetStringer represents a type that can be set from a string value. It is checked in SetRobust.

Jump to

Keyboard shortcuts

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