From db7bf0817e8495dc3974af2a972f3d3f357a4a18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 19 Nov 2024 15:28:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0Map=E4=B8=BANil=E5=88=A4?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- map.go | 37 ++++++++++++++++++++++++++++++++----- map_test.go | 9 +++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/map.go b/map.go index 6de1fd3..46145c4 100644 --- a/map.go +++ b/map.go @@ -9,6 +9,7 @@ package wrapper import ( "errors" + "reflect" "sync" ) @@ -38,7 +39,7 @@ func (m *Map) rUnlock() { // // Date : 18:34 2024/11/6 func (m *Map) Exist(key string) bool { - if nil == m { + if m.IsNil() { return false } m.rLock() @@ -58,7 +59,7 @@ func (m *Map) Exist(key string) bool { // // Date : 15:16 2024/11/19 func (m *Map) Set(field string, value any) error { - if nil == m { + if m.IsNil() { return errors.New("Map is nil") } m.lock() @@ -67,13 +68,39 @@ func (m *Map) Set(field string, value any) error { return nil } +// Del 删除指定的字段 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 15:21 2024/11/19 +func (m *Map) Del(field string) { + if m.IsNil() { + return + } + m.lock() + defer m.unlock() + delete(*m, field) +} + +// IsNil 判断map是否为nil +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 15:22 2024/11/19 +func (m *Map) IsNil() bool { + if nil == m { + return true + } + return reflect.ValueOf(*m).IsNil() +} + // Get ... // // Author : go_developer@163.com<白茶清欢> // // Date : 14:41 2024/11/19 func (m *Map) Get(field string) (any, error) { - if nil == m { + if m.IsNil() { return nil, errors.New("map is nil") } m.rLock() @@ -97,7 +124,7 @@ func (m *Map) Get(field string) (any, error) { // // Date : 14:59 2024/11/19 func (m *Map) GetDefault(field string, defaultValue any, allowNil bool) any { - if nil == m { + if m.IsNil() { return defaultValue } m.rLock() @@ -135,7 +162,7 @@ func (m *Map) Value() Map { // Date : 19:40 2024/11/6 func (m *Map) Clone() Map { newData := map[string]any{} - if nil == m { + if m.IsNil() { return newData } m.rLock() diff --git a/map_test.go b/map_test.go index b5e022e..e57cc26 100644 --- a/map_test.go +++ b/map_test.go @@ -19,3 +19,12 @@ func TestMap_Exist(t *testing.T) { fmt.Println(testData.Exist("name")) fmt.Println(testData.Exist("age")) } + +func TestMap_IsNil(t *testing.T) { + var ( + m Map + m1 *Map + ) + fmt.Println(m.Set("a", 1)) + fmt.Println(m.IsNil(), m1.IsNil()) +}