add struct

This commit is contained in:
fancl 2023-09-12 14:14:09 +08:00
parent c42b2317d6
commit fbb08c6eb4
3 changed files with 59 additions and 6 deletions

View File

@ -1,4 +1,4 @@
package crypto package aes
import ( import (
"bytes" "bytes"

View File

@ -138,6 +138,45 @@ func Set(hacky interface{}, field string, value interface{}) (err error) {
return return
} }
switch fieldKind { switch fieldKind {
case reflect.Struct:
switch rv.Kind() {
case reflect.Map:
keys := rv.MapKeys()
subVal := reflect.New(refField.Type())
for _, key := range keys {
pv := rv.MapIndex(key)
if key.Kind() == reflect.String {
if err = Set(subVal.Interface(), key.String(), pv.Interface()); err != nil {
return err
}
}
}
refField.Set(subVal.Elem())
default:
err = fmt.Errorf("struct unsupported assign kind %s", rv.Kind())
}
case reflect.Ptr:
elemType := refField.Type()
if elemType.Elem().Kind() == reflect.Struct {
switch rv.Kind() {
case reflect.Map:
keys := rv.MapKeys()
subVal := reflect.New(elemType.Elem())
for _, key := range keys {
pv := rv.MapIndex(key)
if key.Kind() == reflect.String {
if err = Set(subVal.Interface(), key.String(), pv.Interface()); err != nil {
return err
}
}
}
refField.Set(subVal)
default:
err = fmt.Errorf("struct unsupported assign kind %s", rv.Kind())
}
} else {
err = fmt.Errorf("ptr can't set kind %s", elemType.Elem().Kind())
}
case reflect.Array, reflect.Slice: case reflect.Array, reflect.Slice:
innerType := refField.Type().Elem() innerType := refField.Type().Elem()
if rv.Kind() == reflect.Array || rv.Kind() == reflect.Slice { if rv.Kind() == reflect.Array || rv.Kind() == reflect.Slice {

View File

@ -1,17 +1,31 @@
package reflection package reflection
import "testing" import (
"fmt"
"testing"
)
type Fakeb struct {
In int `json:"in"`
}
type fake struct { type fake struct {
Name string `json:"name"` Name string `json:"name"`
Age int `json:"age"` Age int `json:"age"`
Usage *Fakeb `json:"usage"`
} }
func TestSetter(t *testing.T) { func TestSetter(t *testing.T) {
dst := &fake{} dst := &fake{}
ms := map[string]string{"name": "aa", "age": "5"} ms := map[string]any{"name": "aa", "age": "5", "usage": map[string]any{"in": 15}}
Setter(dst, ms) err := Setter(dst, ms)
if err != nil {
t.Error(err)
return
}
if dst.Age != 5 { if dst.Age != 5 {
t.Errorf("setter failed") t.Errorf("setter failed")
} else {
fmt.Println(dst.Usage.In)
fmt.Printf("%+v", dst)
} }
} }