新增remove方法用来,删除并返回删除元素

This commit is contained in:
ybq 2018-03-21 16:27:40 +08:00
parent a3647f8e31
commit baf80827aa
2 changed files with 35 additions and 0 deletions

View File

@ -911,6 +911,23 @@ func (c *cache) Delete(k string) {
}
}
// Remove an item from the cache. Does nothing if the key is not in the cache.
// There is delete cache data, return cache data and presence status
func (c *cache) Remove(k string) (interface{}, bool) {
c.mu.Lock()
v, found := c.items[k]
if found {
delete(c.items, k)
c.mu.Unlock()
if c.onEvicted != nil {
c.onEvicted(k, v)
}
return v.Object, true
}
c.mu.Unlock()
return nil, false
}
func (c *cache) delete(k string) (interface{}, bool) {
if c.onEvicted != nil {
if v, found := c.items[k]; found {

View File

@ -1149,7 +1149,25 @@ func TestDelete(t *testing.T) {
t.Error("x is not nil:", x)
}
}
func TestREmove(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("foo", "bar", DefaultExpiration)
data, ok := tc.Remove("foo")
if !ok {
t.Error("foo was not found, It should be discovered")
}
if data != "bar" {
t.Error("foo should be bar ")
}
x, found := tc.Get("foo")
if found {
t.Error("foo was found, but it should have been deleted")
}
if x != nil {
t.Error("x is not nil:", x)
}
}
func TestItemCount(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("foo", "1", DefaultExpiration)