3 // Copyright 2021 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
13 type AnyCacher[T any] interface {
14 // Get an item from the cache. Returns the item or nil, and a bool indicating
15 // whether the key was found.
16 Get(k string) (T, bool)
17 // Add an item to the cache, replacing any existing item.
22 type Item[T any] struct {
26 // AnyCache implements AnyCacher
27 type AnyCache[T any] struct {
31 type anyCache[T any] struct {
32 items map[string]Item[T]
33 janitor *janitor[T] // Needed for the failure in the issue
36 // Set adds an item to the cache, replacing any existing item.
37 func (c *anyCache[T]) Set(k string, x T) {
43 // Get gets an item from the cache. Returns the item or nil, and a bool indicating
44 // whether the key was found.
45 func (c *anyCache[T]) Get(k string) (T, bool) {
46 // "Inlining" of get and Expired
47 item, found := c.items[k]
53 return item.Object, true
56 type janitor[T any] struct {
60 func newAnyCache[T any](m map[string]Item[T]) *anyCache[T] {
67 // NewAny[T any](...) returns a new AnyCache[T].
68 func NewAny[T any]() *AnyCache[T] {
69 items := make(map[string]Item[T])
70 return &AnyCache[T]{newAnyCache(items)}
73 // NewAnyCacher[T any](...) returns an AnyCacher[T] interface.
74 func NewAnyCacher[T any]() AnyCacher[T] {
78 type MyStruct struct {
83 // Create a generic cache.
84 // All items are cached as interface{} so they need to be cast back to their
85 // original type when retrieved.
86 // Failure in issue doesn't happen with 'any' replaced by 'interface{}'
87 c := NewAnyCacher[any]()
89 myStruct := &MyStruct{"MySuperStruct"}
91 c.Set("MySuperStruct", myStruct)
93 myRawCachedStruct, found := c.Get("MySuperStruct")
96 // Casting the retrieved object back to its original type
97 myCachedStruct := myRawCachedStruct.(*MyStruct)
98 fmt.Printf("%s", myCachedStruct.Name)
100 fmt.Printf("Error: MySuperStruct not found in cache")