Clarification about storing pointers; renamed Purge to Flush (like Memcache)
This commit is contained in:
parent
3088a9aad8
commit
848f8b6c3a
25
cache.go
25
cache.go
|
@ -59,7 +59,28 @@ import (
|
||||||
// foo := x.(*MyStruct)
|
// foo := x.(*MyStruct)
|
||||||
// ...
|
// ...
|
||||||
// }
|
// }
|
||||||
|
//
|
||||||
|
// If you store a reference type like a pointer, slice, map or channel, you do not need to
|
||||||
|
// run Set if you modify the underlying data. The cache does not serialize its data, so if
|
||||||
|
// you modify a struct whose pointer you've stored in the cache, retrieving that pointer
|
||||||
|
// with Get will point you to the same data:
|
||||||
|
//
|
||||||
|
// foo := &MyStruct{Num: 1}
|
||||||
|
// c.Set("foo", foo, 0)
|
||||||
|
// ...
|
||||||
|
// x, _ := c.Get("foo")
|
||||||
|
// foo := x.(MyStruct)
|
||||||
|
// fmt.Println(foo.Num)
|
||||||
|
// ...
|
||||||
|
// foo.Num++
|
||||||
|
// ...
|
||||||
|
// x, _ := c.Get("foo")
|
||||||
|
// foo := x.(MyStruct)
|
||||||
|
// foo.Println(foo.Num)
|
||||||
|
//
|
||||||
|
// will print:
|
||||||
|
// 1
|
||||||
|
// 2
|
||||||
|
|
||||||
type Cache struct {
|
type Cache struct {
|
||||||
*cache
|
*cache
|
||||||
|
@ -146,7 +167,7 @@ func (c *cache) DeleteExpired() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deletes all items in the cache
|
// Deletes all items in the cache
|
||||||
func (c *cache) Purge() {
|
func (c *cache) Flush() {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
|
|
@ -95,3 +95,27 @@ func TestCacheTimes(t *testing.T) {
|
||||||
t.Error("Found d when it should have been automatically deleted (later than the default)")
|
t.Error("Found d when it should have been automatically deleted (later than the default)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type TestStruct struct {
|
||||||
|
Num int
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStorePointerToStruct(t *testing.T) {
|
||||||
|
tc := New(0, 0)
|
||||||
|
tc.Set("foo", &TestStruct{Num: 1}, 0)
|
||||||
|
x, found := tc.Get("foo")
|
||||||
|
if !found {
|
||||||
|
t.Fatal("*TestStruct was not found for foo")
|
||||||
|
}
|
||||||
|
foo := x.(*TestStruct)
|
||||||
|
foo.Num++
|
||||||
|
|
||||||
|
y, found := tc.Get("foo")
|
||||||
|
if !found {
|
||||||
|
t.Fatal("*TestStruct was not found for foo (second time)")
|
||||||
|
}
|
||||||
|
bar := y.(*TestStruct)
|
||||||
|
if bar.Num != 2 {
|
||||||
|
t.Fatal("TestStruct.Num is not 2")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue