skip to content
Alvin Lucillo

Implementing multi generic type params

/ 1 min read

The code below implements and uses the generic type Cache with multiple parameters K and V. A map requires its key to be comparable so K is defined with comparable constraint. V can be of any type. Notice that we don’t need to redeclare the constraints in the function receiver because they are already defined in the type declaration type at the top.

type Cache[K comparable, V any] map[K]V // constraints are declared here

func (c Cache[K, V]) Set(key K, value V) {
	c[key] = value
}

func (c Cache[K, V]) Get(key K) (V, bool) {
	value, ok := c[key]
	return value, ok
}

func main() {
	cache := Cache[string, string]{} // defines concrete types
	cache.Set("1", "one")
	v, ok := cache.Get("1")
	fmt.Println(v, ok) // one true
}