Skip to content

Commit 22190cd

Browse files
committed
Dynamic struct
1 parent 3fce074 commit 22190cd

6 files changed

Lines changed: 91 additions & 102 deletions

File tree

secretary/docs/secretary.excalidraw.svg

Lines changed: 2 additions & 2 deletions
Loading

secretary/dynamic_serialization.md

Lines changed: 0 additions & 100 deletions
This file was deleted.
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package dynamicstruct
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"reflect"
7+
"strings"
8+
)
9+
10+
type FieldInfo struct {
11+
Type string `json:"type"`
12+
Enc int `json:"enc,omitempty"`
13+
Size int `json:"size,omitempty"`
14+
}
15+
16+
func Parse(jsonData string) {
17+
// Parse the JSON metadata
18+
var metadata map[string]FieldInfo
19+
err := json.Unmarshal([]byte(jsonData), &metadata)
20+
if err != nil {
21+
panic(err)
22+
}
23+
24+
// Create a dynamic struct based on metadata
25+
fields := []reflect.StructField{}
26+
for name, info := range metadata {
27+
var fieldType reflect.Type
28+
switch info.Type {
29+
case "int":
30+
fieldType = reflect.TypeOf(0)
31+
case "string":
32+
fieldType = reflect.TypeOf("")
33+
default:
34+
continue
35+
}
36+
37+
// Capitalize field name
38+
fieldName := strings.ToUpper(name[:1]) + name[1:]
39+
40+
fields = append(fields, reflect.StructField{
41+
Name: fieldName,
42+
Type: fieldType,
43+
Tag: reflect.StructTag(fmt.Sprintf(`custom:"enc=%d,size=%d"`, info.Enc, info.Size)),
44+
})
45+
}
46+
47+
// Create a struct type dynamically
48+
dynamicType := reflect.StructOf(fields)
49+
instance := reflect.New(dynamicType).Elem()
50+
51+
fmt.Println(dynamicType)
52+
fmt.Println(instance)
53+
54+
// Assign values dynamically
55+
if len(fields) > 0 && fields[0].Type.Kind() == reflect.Int {
56+
instance.Field(0).SetInt(42) // Set int value
57+
}
58+
if len(fields) > 1 && fields[1].Type.Kind() == reflect.String {
59+
instance.Field(1).SetString("abc") // Set string value
60+
}
61+
62+
// Print dynamic struct values
63+
fmt.Println("Dynamically Created Struct:")
64+
for i := 0; i < dynamicType.NumField(); i++ {
65+
field := dynamicType.Field(i)
66+
fmt.Printf("%s: %v\n", field.Name, instance.Field(i).Interface())
67+
}
68+
69+
// Access struct tags
70+
fmt.Println("\nStruct Field Tags:")
71+
for i := 0; i < dynamicType.NumField(); i++ {
72+
field := dynamicType.Field(i)
73+
fmt.Printf("%s tag: %s\n", field.Name, field.Tag)
74+
}
75+
76+
fmt.Println(instance)
77+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package dynamicstruct
2+
3+
import "testing"
4+
5+
func TestParse(t *testing.T) {
6+
jsonData := `{
7+
"a": { "type": "int", "enc": 3 },
8+
"s": { "type": "string", "size": 3 }
9+
}`
10+
11+
Parse(jsonData)
12+
}

0 commit comments

Comments
 (0)