I need a linked node to hold some different interface types, so I made it with generics, but the generics type any
can't be compared to nil, it shows error as in the comment:
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)
}
I also tried to compare with a default value
var nilT T
if n.leaf != nilT { // <-- same problem
And restrict the node type as
type node[T myInterface] struct {
Same error, how to solve this? Thanks.