在解决 Go 中编译时强制执行有效状态转换的问题时,我遇到了函数无法返回具有非具体类型参数的泛型类型的限制,如本问题所述。无法构建的 MRE(Go Playground 链接):
\ntype MyStruct[T any] struct {\n MyField T\n}\n\nfunc returnConstrainedGeneric[T any]() MyStruct[T] {\n return MyStruct[int]{\n MyField: 1,\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n编译器返回错误cannot use MyStruct[int]{\xe2\x80\xa6} (value of type MyStruct[int]) as MyStruct[T] value in return statement。
链接的问题给出了这样的推理:
\n\n\n发生该错误的原因是涉及类型参数的操作(包括赋值和返回)必须对其类型集中的所有类型都有效。
\n
它概述了包括类型断言在内的几种解决方法,但我很好奇为什么会出现此限制。MyStruct[int]天真地,在我的示例中,我希望从 中返回类型的值是有效的returnConstrainedGeneric(),因为int满足 的类型约束any。我希望 的调用者returnConstrainedGeneric()不知道返回值的类型是MyStruct[int],它只知道它MyStruct[T]满足T约束any。我的推理中缺少什么?这是 Go 如何实现泛型/类型约束的基本问题,还是 Go 编译器当前实现的问题,还是其他问题?
这是无效的,因为语法意味着
x:=returnConstrainedGeneric[string]()
// x is MyStruct[string]
Run Code Online (Sandbox Code Playgroud)
但你正试图返回一个MyStruct[int].
您推理中的缺陷是您在实例化函数时指定了函数的返回类型。该函数无法返回满足约束的类型any,它返回实例化的类型。换句话说,实例化的函数必须与 中的 T相同。TMyStruct[T]
如果您总是返回MyStruct[int],请这样声明:
func returnConstrainedGeneric[T any]() MyStruct[int] {...}
Run Code Online (Sandbox Code Playgroud)
T或者,如果该函数根本不使用:
func returnConstrainedGeneric() MyStruct[int] {...}
Run Code Online (Sandbox Code Playgroud)