go-cache icon indicating copy to clipboard operation
go-cache copied to clipboard

First pass at implementing generics

Open lukemassa opened this issue 4 years ago • 0 comments

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:

  1. Not finished (need to implement remainder of cache_test and all of sharded)
  2. 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?
  3. 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
    
  4. Is it possible to reduce duplication of comparable for non-method functions?
  5. It didn't feel right to make janitor dependent 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)
  6. I removed all the Increment* and Decrement* methods since the Increment() and Decrement() methods themselves return the correct concrete type
  7. 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 "+"

lukemassa avatar Dec 30 '21 18:12 lukemassa