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

type opStack[T any] []T

func main() {

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

在操场上,这会在make()次呼叫时发出砰砰声(同样在被注释掉的new次呼叫时),并显示以下错误消息:

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

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

推荐答案

因为你想

t=追加(t,0)

数据类型可以是INT或FLOAT GROUP.

这个代码应该能用

package main

import "fmt"

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

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

Go相关问答推荐

T的Golang通用切片,其中 *T实现接口

我不能让GIO画一个按钮

Golang应用程序:所请求的资源上不存在HTTP-Control-Allow-Origin标头

使用ciph.AEAD.Seal()查看内存使用情况

如何使用GO GIN从Auth0 JWT内标识检索权限

将DATE类型的SQL字段扫描到GO struct 字段

";无效的复制因子;融合Kafka Go客户端

无法读取postman 中的表单数据

Json.Unmarshal() 和 gin.BindJson() 之间的区别

从 ApiGateway 中的 lambda Go 返回 Json

使用Cookie身份验证的Gorilla Golang Websocket优化

判断不同 go map 类型中的重复键

致命错误 - 所有 Goroutines 都睡着了!僵局

regex.ReplaceAll 但如果替换则添加相同数量的字符

为什么 reflect.TypeOf(new(Encoder)).Elem() != reflect.TypeOf(interfaceVariable)?

try 与 golang testify/suite 并行运行测试失败

Golang grpc go.mod 问题

Go:用于 XML 解码的嵌套 struct 中的提升字段

如何允许可转换为指针的泛型类型参数化另一种可转换为指针的泛型类型?

Gin中测试模式有什么用