在学习 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 抱怨什么以及需要纠正什么?
假设我有一个界面:
type Module interface {
Run(moduleInput x) error // x is the type of moduleInput
}
Run Code Online (Sandbox Code Playgroud)
其中每个“模块”将完成该Run功能。但是,它moduleInput不是单个结构 - 它应该能够接受任何结构,但只接受允许的结构,即不接受interface{}(例如,仅moduleAInputs和moduleBInputs结构)。
理想情况下,Run每个模块的函数都具有以下类型,moduleXInput其中 X 是示例模块。
是否可以使用泛型或其他方式限制 的类型moduleInput?