使用不同类型参数实例化泛型类型会产生两个新的不同命名类型。
请注意,每次提供类型参数(包括在函数参数或返回类型中)时,您都在实例化泛型类型:
// Props is instantiated with type argument 'Generic'
func Problem() Props[Generic] {
return ExampleProps
}
所以Props[Example]
只是与以下类型不同Props[Generic]
并且您不能在需要使用一种类型的值时使用另一种类型的值。用作参数的类型本身是否满足某些可分配性条件并不重要,例如接口和实现者。
对于实例化的泛型也是如此any
。方式any
只是另一个静态类型——别名interface{}
。它不等于T
并且它不等于“任何类型”。
简单来说,就好像您正在使用int
where 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 https://gotipplay.golang.org/p/wcDOtJ6z80u