I’m very new to go, still in the phase of learning and couldn’t find any answers matching to my issue, so please don’t downvote.
I have this generic interface which can be instantiated by two type parameters, which I have absolutely no problems making new maps with the types implementing this interface. I also I’m able to insert and index the keys, but I’m facing a problem while trying to return the values from the maps using a generic function. Please help me fix the GetGenericIfaceVal
function mentioned below. The compiler complaints that it cannot return the type c as it is an IncompatibleAssign
.
package main
import (
"strings"
)
type GenericIface[rType ~map[string]T, T interface{}] interface {
GetSubTypes() rType
}
type t1 struct {
subTypes r1
}
type r1 map[string]r1
type t2 struct {
subTypes r2
}
type r2 map[string]t2
var mapFirst = make(map[string]GenericIface[r1, r1])
var mapSecond = make(map[string]GenericIface[r2, t2])
//cannot use mapFirst[cType] (map index expression of type GenericIface[r1, r1]) as c value in return statement compiler (IncompatibleAssign) [29, 12]
func GetGenericIfaceVal[c GenericIface[M, T],M ~map[string]T, T interface{}](cType string) c {
if strings.HasPrefix(cType, "$") {
return mapFirst[cType]
}
return mapSecond[cType]
}
func (t *t1) GetSubTypes() r1 {
return t.subTypes
}
func (t *t2) GetSubTypes() r2 {
return t.subTypes
}