go-superstruct

[library] uses reflection to merge structs
git clone https://hhvn.uk/go-superstruct
git clone git://hhvn.uk/go-superstruct
Log | Files | Refs | LICENSE

commit cf9a966edf23ef7fa8c9ecc5545e4120a8bafa7a
parent 3c2e23cec62015135d117132ca2dd31b066181aa
Author: hhvn <dev@hhvn.uk>
Date:   Sat, 17 Feb 2024 15:36:22 +0000

Follow pointers/interfaces to find struct

Diffstat:
Msuperstruct.go | 19++++++++++++++++---
1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/superstruct.go b/superstruct.go @@ -19,6 +19,18 @@ var ( ErrNotStruct = errors.New("not a structure") ) +func getStruct(v reflect.Value) (reflect.Value, error) { + for (v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface) { + v = v.Elem() + } + + if v.Kind() == reflect.Struct { + return v, nil + } else { + return v, ErrNotStruct + } +} + func copyWalk(vdst, src reflect.Value) { dst := vdst.Elem() @@ -71,9 +83,10 @@ func copyWalk(vdst, src reflect.Value) { func do(cp bool, in... interface{}) (interface{}, error) { v := make([]reflect.Value, len(in)) for i := range in { - v[i] = reflect.ValueOf(in[i]) - if v[i].Kind() != reflect.Struct { - return nil, ErrNotStruct + var err error + v[i], err = getStruct(reflect.ValueOf(in[i])) + if err != nil { + return nil, err } }