I'm just now starting to work with generics for a project. I've set up the following example in a go playground. I'm trying to create a generic function to reset the cache of 2 different types, that have the same fields. Furthermore, I can't figure out why I can't access those fields withing the generic function.
The error is:
./prog.go:21:4: c.Count undefined (type *C is pointer to type parameter, not type parameter)
./prog.go:22:4: c.List undefined (type *C is pointer to type parameter, not type parameter)
Any help is appreciated.
https://go.dev/play/p/ojkNe1D-hSE
package main
import "fmt"
type CacheOne struct {
Count int
List []string
}
type CacheTwo struct {
Count int
List []string
}
type cachable interface {
CacheOne | CacheTwo
}
// resetSCache resets the Count & List of a given cachable type.
func resetCache[C cachable](c *C) {
c.Count = 0
c.List = []string{}
}
func main() {
// Example usage
dOne := &CacheOne{
Count: 5,
List: []string{"hello", "world"},
}
dTwo := &CacheTwo{
Count: 5,
List: []string{"hello", "world"},
}
fmt.Println("Before reseting...whould be populated with data")
fmt.Println(dOne)
fmt.Println(dTwo)
resetCache(dOne)
resetCache(dTwo)
fmt.Println("Before reseting...whould be reset with zero values")
fmt.Println(dOne)
fmt.Println(dTwo)
}