From a0ce778e6e0c324d85045eb762d4a99573e533bd Mon Sep 17 00:00:00 2001 From: arraykeys Date: Tue, 9 Jan 2024 12:46:19 +0800 Subject: [PATCH] gvalue MapToStruct --- util/value/value.go | 7 +++++++ util/value/value_test.go | 6 +++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/util/value/value.go b/util/value/value.go index ed6fa848..225d7575 100644 --- a/util/value/value.go +++ b/util/value/value.go @@ -1184,6 +1184,10 @@ var typeOfBytes = reflect.TypeOf([]byte(nil)) // if 'mkey' not exists the filed name will used as map key, for example: User{} or new(User). // Returned newStruct is a struct, for example: newStruct.(User) to assert it type. // Details refer to TestMapToStruct. +// Ignore filed, set tag mkey:"-", for example: +// User{ +// Age int `mkey:"-"` +// } func MapToStruct(mapData map[string]interface{}, _value interface{}, tagName ...string) (newStruct interface{}, err error) { if IsNil(_value) || (reflect.TypeOf(_value).Kind() != reflect.Struct && reflect.TypeOf(_value).Kind() != reflect.Ptr) { @@ -1218,6 +1222,9 @@ func MapToStruct(mapData map[string]interface{}, _value interface{}, tagName ... fieldKind = fieldType.Kind() } col := strings.Split(field.Tag.Get(tag), ",")[0] + if col == "-" { + continue + } val, ok := mapData[col] if !ok { val, ok = mapData[field.Name] diff --git a/util/value/value_test.go b/util/value/value_test.go index fa61384a..a9e5ee08 100644 --- a/util/value/value_test.go +++ b/util/value/value_test.go @@ -538,7 +538,9 @@ type YourStruct struct { ErrStructField YourInnerStruct MapKey int8 `mkey:"key1"` privateField int - MapField map[string]interface{} //map field only map[string]interface{} supported + //map field only map[string]interface{} supported + MapField map[string]interface{} + IgnoreField int `mkey:"-"` } type YourInnerStruct struct { @@ -587,6 +589,7 @@ func TestMapToStruct(t *testing.T) { "key1": int8(8), "privateField": 1, "MapField": map[string]string{"abc": "123"}, + "IgnoreField": 1, } for _, v := range []interface{}{YourStruct{}, new(YourStruct)} { @@ -618,6 +621,7 @@ func TestMapToStruct(t *testing.T) { assert.Equal(t, "nested", yourStruct.PtrStructField.InnerStrField) assert.Equal(t, 0, yourStruct.privateField) assert.Equal(t, "123", yourStruct.MapField["abc"]) + assert.Equal(t, 0, yourStruct.IgnoreField) } // 测试第二个参数是不同的结构体的情况 result, err := MapToStruct(mapData, YourSecondStruct{})