Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache implements a lazy initializing cache. A cache entry is created the first time a value is accessed (via Get or MustGet) by invoking the provided Initializer. If the Initializer returns an error then the entry will not be added.
func New ¶
func New(name string, initializer EntryInitializer) *Cache
New creates a new lazy cache with the given name (Note that the name is only used for debugging purpose)
func (*Cache) Close ¶
func (c *Cache) Close()
Close does the following: - calls Close on all values that implement a Close() function - deletes all entries from the cache - prevents further calls to the cache
func (*Cache) Get ¶
Get returns the value for the given key. If the key doesn't exist then the initializer is invoked to create the value, and the key is inserted. If the initializer returns an error then the key is removed from the cache.
Example ¶
cache := New("Example_Cache", func(key Key) (interface{}, error) { if key.String() == "error" { return nil, fmt.Errorf("some error") } return fmt.Sprintf("Value_for_key_%s", key), nil }) defer cache.Close() value, err := cache.Get(NewStringKey("Key1")) if err != nil { fmt.Printf("Error returned: %s\n", err) } fmt.Println(value) value, err = cache.Get(NewStringKey("error")) if err != nil { fmt.Printf("Error returned: %s\n", err) } fmt.Println(value)
Output:
func (*Cache) MustGet ¶
MustGet returns the value for the given key. If the key doesn't exist then the initializer is invoked to create the value and the key is inserted. If an error is returned during initialization of the value then this function will panic.
Example ¶
cache := New("Example_Cache", func(key Key) (interface{}, error) { return fmt.Sprintf("Value_for_key_%s", key), nil }) defer cache.Close() key := NewStringKey("Key1") fmt.Println(cache.MustGet(key))
Output: Value_for_key_Key1
type EntryInitializer ¶
EntryInitializer creates a cache value for the given key