#generics in method receivers

6 messages · Page 1 of 1 (latest)

zinc plank
#

Hi there, I am trying to implement a binary tree in go using generics.

type Node[T comparable] struct {
    value T
    left *Node[T]
    right *Node[T]
}

func (n *Node[T]) insert(value T)  {
    if n == nil {
        return
    }
    if value > n.value {
        if n.right == nil {
            n.right = &Node[T]{value: value}
        } else {
            n.right.insert(value)
        }
    } else {
        if n.left == nil {
            n.left = &Node[T]{value: value}
        } else {
            n.left.insert(value)
        }
    }
}

type BinarySearchTree[T comparable] struct {
    root Node[T]
}

The code doesn't compile and gives this error: invalid operation: value > n.value (type parameter T is not comparable with >). I already specified the type constraint of Node above to be comparable. What am I doing wrong?

oblique eagle
#

> is not for comparable, that's called Ordered

#

Comparable is just equal and not equal

silent bladeBOT
#

    type comparable interface{ comparable }

comparable is an interface that is implemented by all comparable types (booleans, numbers, strings, pointers, channels, arrays of comparable types, structs whose fields are all comparable types). The comparable interface may only be used as a type parameter constraint, not as the type of a variable.

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

Note that floating-point types may contain NaN ("not-a-number") values. An operator such as == or < will always report false when comparing a NaN value with any other value, NaN or not. See the Compare function for a consistent way to compare NaN values.

cmp.go

tall ridge