我在 Go 中有一些通用代码,其中有一个具有通用参数的“主”类型和许多应共享相同通用参数的“从”类型。代码看起来类似于:
type Doer[T any] interface {
ModifyA(*A[T])
}
type B[T any] struct {
}
func NewB[T any]() *B[T] {
return new(B[T])
}
func (b *B[T]) ModifyA(a *A[T]) {
// Do a thing
}
type A[T any] struct{}
func NewA[T any]() A[T] {
return A[T]{}
}
func (a *A[T]) Run(doers ...Doer[T]) {
for _, doer := range doers {
doer.ModifyA(a)
}
}
func main() {
a := new(A[int])
a.Run(NewB()) // error here
}
基本上,用户应该在
T
上定义A
然后在T
上定义B
应该是相同的。这种代码可以在其他支持泛型的语言中运行,但在 Go 中,我在注释行中得到一个cannot infer T
编译错误(参见 Go playground 代码,here)。在我看来,a
上的类型参数设置为 int
,因此 B
上的类型参数也应设置为 int
。我可以改为调用NewB[int]()
,但这对我来说似乎过于冗长。为什么会这样?