为什么一个泛型不能分配给另一个泛型,即使它们的类型参数可以?



以下代码引发编译错误

不能在返回语句中将ExampleProps(Props[Example]类型的变量(用作Props[Generic]值

// Abstract
type Generic interface {
ID() string
}
type Props[G Generic] struct{}
// Example
type Example struct {
id string
}
func (example Example) ID() string {
return example.id
}
var ExampleProps = Props[Example]{}
// Problem
func Problem() Props[Generic] {
return ExampleProps
}

我的问题是:既然Example实现了Generic,为什么Go不允许将Props[Example]分配给Props[Generic]

用不同的类型参数实例化泛型类型会生成两个新的不同命名类型。

请注意,每次提供类型参数时,包括在函数参数或返回类型中,都是在实例化泛型类型:

// Props is instantiated with type argument 'Generic'
func Problem() Props[Generic] {
return ExampleProps
}

因此,Props[Example]Props[Generic]的类型不同,并且不能在期望使用一种类型的值的地方使用另一种类型。用作参数的类型本身是否满足可分配性的某些条件并不重要,例如接口和实现器。

使用any实例化的泛型也是如此。类型any只是另一个静态类型——interface{}的别名。它不等于CCD_ 10;任何类型";。

简单地说,就好像您在使用int,而string是预期的。

您可以修复它并保持一定的灵活性的是用类型参数实例化Props——这是否有意义取决于您实际计划如何使用此函数。无论如何,作为演示:

// adding a field to make this a bit less contrived
type Props[G Generic] struct{ Value G }
// Props instantiated with T, adequately constrained
func Problem[T Generic](v T) Props[T] {
return Props[T]{ Value: v }
}
func main() {
a := Problem(Example{})
fmt.Println(a)
}

游乐场:https://gotipplay.golang.org/p/wcDOtJ6z80u

最新更新