Golang运行时动态生成结构体

This commit is contained in:
2025-03-19 15:27:14 +08:00
commit eab2a7abde
7 changed files with 771 additions and 0 deletions

41
builder_test.go Normal file
View File

@ -0,0 +1,41 @@
// Package dynamicstruct ...
//
// Description : dynamicstruct ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-03-19 14:48
package dynamicstruct
import (
"encoding/json"
"fmt"
"reflect"
"testing"
)
func Test_dynamicStructImpl_New(t *testing.T) {
instance := NewStruct().
AddField("Integer", "", 0, `json:"int"`, false).
AddField("Text", "", "", `json:"someText"`, false).
AddField("Float", "", 0.0, `json:"double"`, false).
AddField("Boolean", "", false, "", false).
AddField("Slice", "", []int{}, "", false).
AddField("Anonymous", "", "", `json:"-"`, false).
Build().
New()
data := []byte(`
{
"int": 123,
"someText": "example",
"double": 123.45,
"Boolean": true,
"Slice": [1, 2, 3],
"Anonymous": "avoid to read"
}
`)
err := json.Unmarshal(data, &instance)
fmt.Println(err)
fmt.Println(reflect.ValueOf(instance).Elem().FieldByName("Integer").Interface())
}