我正在尝试使用泛型实现接口Interface
。它有一个方法,该方法接受另一个接口作为参数:
type SubInterface interface {
SendResponse(string)
}
type Interface interface {
Subscribe(SubInterface)
}
我已经想出了以下这些接口的通用版本:
type GenericSubInterface[T any] interface {
SendResponse(T)
}
type GenericInterface[Res any] interface {
Subscribe(GenericSubInterface[Res])
}
我希望 `GenericInterface[string]` 可以赋值给 `Interface`,但它似乎并不能。
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
创建一个通用的Interface
实现也不起作用:
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]{}
对我来说奇怪的是,子接口可以相互赋值:
var d SubInterface
var e GenericSubInterface[string]
// works fine
d = e
当接口以某种方式嵌套时,问题似乎只会出现。有没有办法绕过这个问题,我可以使用泛型来实现除了字符串之外的其他类型的Interface
?