go-cache
go-cache copied to clipboard
First pass at implementing generics
Replaces #128
Makes the cache generically typed using (as of yet not released) go generics, so clients code looks like:
c := cache.New[int](cache.DefaultExpiration, 0)
c.Set("foo", 5, cache.DefaultExpiration)
c.Increment("foo", 1)
value, _ := c.Get("foo")
fmt.Printf("5+1=%d\n", value+1)
Some open issues/questions:
- Not finished (need to implement remainder of cache_test and all of sharded)
- Current implementation is NOT backwards compatible (type inference doesn't work in general and client code must say e.g.
cache.New[int](...)) a. TODO: Is this possible to fix? - This code won't compile without generics, so to test you'll need to have a local copy of go1.18 (https://go.dev/doc/tutorial/generics#installing_beta)
luke@LMASSA-MAC go-cache % go test ./... # github.com/patrickmn/go-cache [github.com/patrickmn/go-cache.test] ./cache.go:13:14: syntax error: unexpected comparable, expecting ] ./cache.go:19:16: syntax error: unexpected [, expecting comma or ) ./cache.go:35:15: syntax error: unexpected comparable, expecting ] ./cache.go:42:15: syntax error: unexpected comparable, expecting ] ./cache.go:46:35: method has multiple receivers ./cache.go:46:35: syntax error: unexpected newline, expecting name or ( ./cache.go:47:2: syntax error: non-declaration statement outside function body luke@LMASSA-MAC go-cache % ~/go/bin/go1.18beta1 test ./... ok github.com/patrickmn/go-cache 0.549s - Is it possible to reduce duplication of
comparablefor non-method functions? - It didn't feel right to make
janitordependent on type, but that meant converting Run() from a method to a function (https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#No-parameterized-methods) - I removed all the
Increment*andDecrement*methods since theIncrement()andDecrement()methods themselves return the correct concrete type - On that note, Increment and Decrement are not type-safe, which replicates the behavior of the current implementation. Some ideas there: a. Leave as is (no worse than non-generic) b. Have an "IncrementableCache" type that takes a generic typeset that would allow us to use "+"