From e4cef0855e8af82d175af6af9a3179a2edbb2b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Wed, 21 Aug 2024 17:09:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A8=E6=80=81=E7=94=9F=E6=88=90=E7=BB=93?= =?UTF-8?q?=E6=9E=84=E4=BD=93=E7=9A=84=E5=9F=BA=E7=A1=80=E8=83=BD=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dynamic_struct.go | 98 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 dynamic_struct.go diff --git a/dynamic_struct.go b/dynamic_struct.go new file mode 100644 index 0000000..3924d5e --- /dev/null +++ b/dynamic_struct.go @@ -0,0 +1,98 @@ +// Package wrapper ... +// +// Description : wrapper ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2024-08-21 16:43 +package wrapper + +import "reflect" + +func NewDynamic() *DynamicStruct { + return &DynamicStruct{ + structFieldList: make([]reflect.StructField, 0), + } +} + +// DynamicStruct 动态生成数据结构 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:48 2024/8/21 +type DynamicStruct struct { + structFieldList []reflect.StructField // 结构体字段列表 +} + +func (ds *DynamicStruct) AddInt() { + +} + +func (ds *DynamicStruct) AddUint() { + +} + +func (ds *DynamicStruct) AddString() { + +} + +func (ds *DynamicStruct) AddBool() { + +} + +func (ds *DynamicStruct) AddFloat() { + +} + +func (ds *DynamicStruct) AddSlice() { + +} + +func (ds *DynamicStruct) AddMap() { + +} + +func (ds *DynamicStruct) AddStructField() { + +} + +// GetStructType 获取结构体的类型 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:58 2024/8/21 +func (ds *DynamicStruct) GetStructType() reflect.Type { + return reflect.StructOf(ds.structFieldList) +} + +// ToStructDefaultValue 获取结构体的值, 并采用对应类型默认值填充相关字段 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:56 2024/8/21 +func (ds *DynamicStruct) ToStructDefaultValue() any { + defer ds.Clear() + defaultValue := reflect.New(ds.GetStructType()).Elem().Interface() + return defaultValue +} + +// ToStructDefaultSliceValue 自动生成结构体列表 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 17:04 2024/8/21 +func (ds *DynamicStruct) ToStructDefaultSliceValue() any { + defer ds.Clear() + tSlice := reflect.MakeSlice(reflect.SliceOf(ds.GetStructType()), 0, 0) + return reflect.New(tSlice.Type()).Elem().Interface() +} + +// Clear 清理 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 17:08 2024/8/21 +func (ds *DynamicStruct) Clear() { + // 清理掉已设置的字段, 不然实例复用会互相影响 + ds.structFieldList = make([]reflect.StructField, 0) +}