diff --git a/dictionary.go b/dictionary.go index 9a04335..010e2f9 100644 --- a/dictionary.go +++ b/dictionary.go @@ -41,6 +41,16 @@ func (receiver *Dictionary[TKey, TValue]) Add(key TKey, value TValue) { receiver.source[key] = value } +// Update 更新元素 +func (receiver *Dictionary[TKey, TValue]) Update(key TKey, f func(value *TValue)) { + receiver.lock.Lock() + defer receiver.lock.Unlock() + + v := receiver.source[key] + f(&v) + receiver.source[key] = v +} + // Clear 清除元素 func (receiver *Dictionary[TKey, TValue]) Clear() { receiver.lock.Lock() diff --git a/test/dictionary_test.go b/test/dictionary_test.go index 238b87d..8a46d67 100644 --- a/test/dictionary_test.go +++ b/test/dictionary_test.go @@ -56,6 +56,17 @@ func Test_dictionary_Add(t *testing.T) { assert.Equal(t, "boy", dic.GetValue("sex")) } +func Test_dictionary_Update(t *testing.T) { + maps := make(map[string]string) + maps["name"] = "steden" + maps["age"] = "18" + dic := collections.NewDictionaryFromMap[string, string](maps) + dic.Update("name", func(value *string) { + *value = "tao" + }) + assert.Equal(t, "tao", dic.GetValue("name")) +} + func TestDictionary_AddMap(t *testing.T) { dic := collections.NewDictionary[string, int]() maps := map[string]int{"age": 18}