我需要一个链接 node 来保存一些不同的接口类型,所以我用泛型创建了它,但泛型类型any
不能与nil进行比较,它显示错误,如注释中所示:
package main
type myInterface interface {
}
type node[T any] struct {
next *node[T]
leaf T
}
func (n *node[T]) GetFirstNodeHasLeaf() *node[T] {
if n.leaf != nil { // <---- error here: cannot compare n.leaf != nil (mismatched types T and untyped nil)
return n
}
if n.next == nil {
return nil
} else {
return n.next.GetFirstNodeHasLeaf()
}
}
func main() {
var n = &node[myInterface]{}
// fill n with lots of nodes
n.GetFirstNodeHasLeaf() // get the first node that has (leaf != nil)
}
我还try 与缺省值进行比较
var nilT T
if n.leaf != nilT { // <-- same problem
并将 node 类型限制为
type node[T myInterface] struct {
同样的错误,如何解决这个问题?谢谢.