Lui*_*mez 5 generics instantiation variable-assignment go
以下代码会引发编译错误
不能在 return 语句中使用 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
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:作为Example实现Generic,为什么Go不允许分配Props[Example]给Props[Generic]?
使用不同类型参数实例化泛型类型会产生两个新的不同命名类型。
\n请注意,每次提供类型参数(包括在函数参数或返回类型中)时,您都在实例化泛型类型:
\n// Props is instantiated with type argument \'Generic\'\nfunc Problem() Props[Generic] {\n return ExampleProps\n}\nRun Code Online (Sandbox Code Playgroud)\n因此Props[Example],与类型不同,Props[Generic]并且您不能在需要使用一种类型的值时使用另一种类型的值。用作参数的类型本身是否满足可分配性的某些条件(例如接口和实现者)并不重要。
对于用 实例化的泛型也是如此any。该类型any只是 的另一个静态类型 \xe2\x80\x94 别名interface{}。它不等于T也不等于“任何类型”。
简单来说,它 \xe2\x80\x99s 就好像您正在使用预期的int位置一样。string
您可以修复它并保持一定的灵活性,即Props使用类型参数 \xe2\x80\x94 进行实例化,这是否有意义取决于您实际计划如何使用此函数。无论如何,作为演示:
// adding a field to make this a bit less contrived\ntype Props[G Generic] struct{ Value G }\n\n// Props instantiated with T, adequately constrained\nfunc Problem[T Generic](v T) Props[T] {\n return Props[T]{ Value: v }\n}\n\nfunc main() {\n a := Problem(Example{})\n fmt.Println(a)\n}\nRun Code Online (Sandbox Code Playgroud)\n游乐场:https://gotipplay.golang.org/p/wcDOtJ6z80u
\n