Go错误:无法在没有实例化的情况下使用泛型类型

pla*_*guy 35 generics go

在学习 Go 泛型时,我遇到了一个似乎无法解决的错误。我把它归结为最简单的代码:

type opStack[T any] []T

func main() {

    t := make(opStack)
    //  t := new(opStack)
    t = append(t, 0)
    fmt.Println(t[0])
}
Run Code Online (Sandbox Code Playgroud)

在操场上,这会在调用时(以及在注释掉的调用make()上类似)出现问题,并显示以下错误消息:new

无法在没有实例化的情况下使用泛型类型 opStack[T any]

但是make()是一个实例化函数。所以,我希望我错过了一些语法上的微妙之处。Go 抱怨什么以及需要纠正什么?

bla*_*een 32

每当您使用参数化类型时,包括需要类型参数的任何地方(例如在built-in中)make,您都必须将其定义中的类型参数替换为实际类型。这称为实例化。

\n
t := make(opStack[int], 0)\nt = append(t, 0)\n
Run Code Online (Sandbox Code Playgroud)\n

如果将泛型类型用作另一个泛型类型的类型参数,则也必须实例化该泛型类型:

\n
type Data[T any] struct {\n    data T\n}\n\nd := Data[opStack[int]]{ data: []int{0, 1, 2} }\n
Run Code Online (Sandbox Code Playgroud)\n

您可以使用类型参数进行实例化,例如在函数签名、字段和类型定义中:

\n
type FooBar[T any] struct {\n    ops opStack[T]\n}\n\ntype OpsMap[T any] map[string]opStack[T]\n\nfunc echo[T any](ops opStack[T]) opStack[T] { return ops }\n
Run Code Online (Sandbox Code Playgroud)\n

语言规范中的相关引用(当前)位于两个不同的地方,类型定义:

\n
\n

如果类型定义指定类型参数,则类型名称表示泛型类型。泛型类型在使用时必须实例化。

\n
\n

和实例化

\n
\n

泛型函数或类型是通过用类型实参替换类型形参来实例化的。[...]

\n
\n

在其他编程语言中,“实例化”可能指在 Go 中创建对象 \xe2\x80\x94 的实例,该术语特指用具体类型替换类型参数。在我看来,该术语的用法仍然是一致的,尽管在 Go 中它并不一定意味着分配。

\n
\n

请注意,您可以在没有显式类型参数的情况下调用泛型函数。实例化也发生在那里,简单来说,类型参数都可以从函数参数中推断出来:

\n
func Print[T, U any](v T, w U) { /* ... */ }\n\nPrint("foo", 4.5) // T is inferred from "foo", U from 4.5\n
Run Code Online (Sandbox Code Playgroud)\n

推理过去也适用于泛型类型,但限制是类型参数列表必须非空。但是此功能已被禁用,因此您必须显式提供所有类型参数。

\n
type Vector[T any] []T \n// v := Vector[int]{} -> must supply T\n\ntype Matrix[T any, U ~[]T] []U \n// m := Matrix[int, []int]{} -> must supply T and U\n
Run Code Online (Sandbox Code Playgroud)\n