Skip to content

Commit

Permalink
更新
Browse files Browse the repository at this point in the history
  • Loading branch information
steden committed Oct 10, 2024
1 parent 4d6906f commit a163f7b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions dictionary.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
11 changes: 11 additions & 0 deletions test/dictionary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down

0 comments on commit a163f7b

Please sign in to comment.