Documentation
¶
Overview ¶
Package structs provides utilities for inspecting and manipulating Go struct types using reflection.
Use this package when you need to extract metadata from struct types, access field values by name, or assign string-encoded values to struct fields. The package handles embedded anonymous structs and supports various field types including basic types, complex types (maps, slices, structs), and types implementing encoding.TextUnmarshaler.
Field metadata includes the field's type, struct tags parsed into a map, and the chain of anonymous struct names for embedded fields.
Index ¶
- func AssignToField[T any](obj *T, fieldName string, stringEncodedValue string) error
- func Metadata[T any]() map[string]*FieldMetadata
- func MetadataFromType(reflectType reflect.Type) map[string]*FieldMetadata
- func ValueFromName[T any](structInstance T, fieldName string) (reflect.Value, error)
- type FieldMetadata
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AssignToField ¶
AssignToField sets a struct field specified by its name to a provided value encoded as a string. The function handles various data types including basic types (string, int, etc.), complex types (structs, slices, maps) and types implementing the encoding.TextUnmarshaler interface. The conversion from string to the appropriate type is performed based on the field's underlying type. JSON format is expected for complex types. This function supports setting both direct values and pointers to the values.
func Metadata ¶
func Metadata[T any]() map[string]*FieldMetadata
Metadata returns a map of a struct's field names to their respective metadata.
func MetadataFromType ¶
func MetadataFromType(reflectType reflect.Type) map[string]*FieldMetadata
MetadataFromType returns a map of a struct's field names to their respective metadata.
Types ¶
type FieldMetadata ¶
type FieldMetadata struct {
// contains filtered or unexported fields
}
FieldMetadata is the metadata extracted from a structs field.
func (*FieldMetadata) Anonymous ¶
func (f *FieldMetadata) Anonymous() []string
Anonymous returns the anonymous struct name chain before getting to a field.
type DeepExample struct {
DeepField string
}
type Example struct {
DeepExample
Field string
}
If calling Anonymous on the struct Example and the field DeepField, ["DeepExample"] would be returned.
func (*FieldMetadata) Tags ¶
func (f *FieldMetadata) Tags() map[string]string
Tags returns a map of tag names to its respective tag content.
func (*FieldMetadata) Type ¶
func (f *FieldMetadata) Type() reflect.Type
Type returns the fields type.