I'm trying to implement the interface Interface using generics. It has one method which accepts another Interface as a parameter:
type SubInterface interface {
SendResponse(string)
}
type Interface interface {
Subscribe(SubInterface)
}
I've come up with the following generic version of those interfaces:
type GenericSubInterface[T any] interface {
SendResponse(T)
}
type GenericInterface[Res any] interface {
Subscribe(GenericSubInterface[Res])
}
I would expect GenericInterface[string] to be assignable to Interface but it somehow isn't.
var a Interface
var b GenericInterface[string]
// cannot use b (variable of type GenericInterface[string]) as Interface value in assignment: GenericInterface[string] does not implement Interface (wrong type for method Subscribe)
// have Subscribe(GenericSubInterface[string])
// want Subscribe(SubInterface)
a = b
Creating a generic implementation of Interface doesn't work either:
type GenericImplementation[Res any] struct {
}
func (i *GenericImplementation[Res])Subscribe(ss GenericSubInterface[Res]) {
var msg Res
ss.SendResponse(msg)
}
// cannot use &GenericImplementation[string]{} (value of type *GenericImplementation[string]) as Interface value in variable declaration: *GenericImplementation[string] does not implement Interface (wrong type for method Subscribe)
// have Subscribe(GenericSubInterface[string])
// want Subscribe(SubInterface)
var c Interface = &GenericImplementation[string]{}
What seems weird to me is that the sub-interfaces are assignable to each other:
var d SubInterface
var e GenericSubInterface[string]
// works fine
d = e
The problem only seems to occur when interfaces are nested somehow. Is there any way around this that I can implement Interface using generics for types other than string?