reflectx

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2024 License: BSD-3-Clause Imports: 18 Imported by: 8

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

func NewFrom(v reflect.Value) reflect.Value

NewFrom returns a value that is guaranteed to be a pointer to the Underlying version of the given value. If that value is not addressable, it makes a new fake pointer that points to a copy of the value, not the actual value. This should only be used you do not need the pointer to actually point to the original value.

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. If a field implements ShouldSaver and returns false, it will 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(parent reflect.Value) int

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

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 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(v 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 an indented 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 Underlying added in v0.2.0

func Underlying(v reflect.Value) reflect.Value

Underlying returns the actual underlying version of the given value, going through any pointers and interfaces.

func UnderlyingPointer added in v0.2.0

func UnderlyingPointer(v reflect.Value) reflect.Value

UnderlyingPointer returns a pointer to the actual underlying version of the given value, going through any pointers and interfaces.

func ValueIsDefault added in v0.2.0

func ValueIsDefault(fv reflect.Value, def string) bool

ValueIsDefault returns whether the given value is equivalent to the given string representation used in a field default tag.

func ValueSliceSort

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

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

func WalkFields added in v0.2.0

func WalkFields(parent reflect.Value, should func(parent reflect.Value, field reflect.StructField, value reflect.Value) bool, walk func(parent reflect.Value, parentField *reflect.StructField, field reflect.StructField, value reflect.Value))

WalkFields calls the given walk function on all the exported primary fields of the given parent struct value, including those on anonymous embedded structs that this struct has. It effectively flattens all of the embedded fields of the struct.

It passes the current parent struct, current reflect.StructField, and current field value to the given should and walk functions.

The given should function is called on every struct field (including on embedded structs themselves) to determine whether that field and any fields it has embedded should be handled (a return value of true indicates to continue down and a value of false indicates to not).

Types

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

type SetColorer interface {
	SetColor(c color.Color)
}

SetColorer represents a type that can be set from a color 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.

type ShouldSaver added in v0.2.1

type ShouldSaver interface {

	// ShouldSave returns whether this value should be included in the
	// result of [NonDefaultFields].
	ShouldSave() bool
}

ShouldSaver is an interface that types can implement to specify whether a value should be included in the result of NonDefaultFields.

Jump to

Keyboard shortcuts

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