Skip to content

Commit baf8082

Browse files
author
ybq
committed
新增remove方法用来,删除并返回删除元素
1 parent a3647f8 commit baf8082

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

cache.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -911,6 +911,23 @@ func (c *cache) Delete(k string) {
911911
}
912912
}
913913

914+
// Remove an item from the cache. Does nothing if the key is not in the cache.
915+
// There is delete cache data, return cache data and presence status
916+
func (c *cache) Remove(k string) (interface{}, bool) {
917+
c.mu.Lock()
918+
v, found := c.items[k]
919+
if found {
920+
delete(c.items, k)
921+
c.mu.Unlock()
922+
if c.onEvicted != nil {
923+
c.onEvicted(k, v)
924+
}
925+
return v.Object, true
926+
}
927+
c.mu.Unlock()
928+
return nil, false
929+
}
930+
914931
func (c *cache) delete(k string) (interface{}, bool) {
915932
if c.onEvicted != nil {
916933
if v, found := c.items[k]; found {

cache_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1149,7 +1149,25 @@ func TestDelete(t *testing.T) {
11491149
t.Error("x is not nil:", x)
11501150
}
11511151
}
1152+
func TestREmove(t *testing.T) {
1153+
tc := New(DefaultExpiration, 0)
1154+
tc.Set("foo", "bar", DefaultExpiration)
1155+
data, ok := tc.Remove("foo")
1156+
if !ok {
1157+
t.Error("foo was not found, It should be discovered")
1158+
}
1159+
if data != "bar" {
1160+
t.Error("foo should be bar ")
1161+
}
11521162

1163+
x, found := tc.Get("foo")
1164+
if found {
1165+
t.Error("foo was found, but it should have been deleted")
1166+
}
1167+
if x != nil {
1168+
t.Error("x is not nil:", x)
1169+
}
1170+
}
11531171
func TestItemCount(t *testing.T) {
11541172
tc := New(DefaultExpiration, 0)
11551173
tc.Set("foo", "1", DefaultExpiration)

0 commit comments

Comments
 (0)