Go error: cannot use generic type without instantiation

Go error: cannot use generic type without instantiation

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

type opStack[T any] []T

func main() {

    t := make(opStack)
    //  t := new(opStack)
    t = append(t, 0)
    fmt.Println(t[0])
}

在 playground 中,这会在 make() 调用(以及类似地在被注释掉的 new 调用上)出现以下错误消息:

cannot use generic type opStack[T any] without instantiation

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

因为你想要

t = append(t, 0)

数据类型可以是int或float组。

此代码应该有效

package main

import "fmt"

func main() {
    type opStack[T any] []T

    t := make(opStack[int], 0) // You must initialize data type here
    t = append(t, 0)
    fmt.Println(t[0])
}

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

t := make(opStack[int], 0)
t = append(t, 0)

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

type Data[T any] struct {
    data T
}

d := Data[opStack[int]]{ data: []int{0, 1, 2} }

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

type FooBar[T any] struct {
    ops opStack[T]
}

type OpsMap[T any] map[string]opStack[T]

func echo[T any](ops opStack[T]) opStack[T] { return ops }

语言规范的相关引述(目前)在两个不同的地方,Type definitions:

If the type definition specifies type parameters, the type name denotes a generic type. Generic types must be instantiated when they are used.

Instantiations

A generic function or type is instantiated by substituting type arguments for the type parameters. [...]

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


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

func Print[T, U any](v T, w U) { /* ... */ }

Print("foo", 4.5) // T is inferred from "foo", U from 4.5

推理过去也适用于泛型 types,但限制是类型参数列表必须是 non-empty。但是,此功能已被禁用,因此您必须明确提供所有类型参数。

type Vector[T any] []T 
// v := Vector[int]{} -> must supply T

type Matrix[T any, U ~[]T] []U 
// m := Matrix[int, []int]{} -> must supply T and U