How to refer to data type of self in interface definition golang?

Viewed 25

My goal is to do something as simple as creating an interface which supports a binary operation. Suppose the operation name is Op.

So the closest I could come was:

type SupportsOp interface {
    Op(v SupportsOp) bool
}

which really does not meet the needs. According to above code, a SupportOp interface type should have an Op function that supports all SupportsOp types.

func (s1 string) Op(s2 string) bool{
    // some definition
}

What I want is, to be able to define operations as above and be able to accept only those data types which support such operations.

Is there a way to do this?

Consider the following example

package Comparable
type Comparable[T any] interface {
    Equals(T) bool
}

type Ordered[T any] interface {
    Comparable[T]
    LessThan(T) bool
}
package avltree



type AVLNode[T Comparable.Ordered[T]] struct {
    Key         T
    Left, Right *AVLNode[T]
    height      int
}

So T Comparable.Ordered[T] constrains the type to be comparable to themselves. This achieves what I want. But I am not able to abstract this requirement into an interface.

I want to know that is there a way I can define an interface, the types of which are erquired to be self-comparable.

I believe it will be a form similar to:

type X inerface{
    Comparable.Ordered[self]
}

Then this code (this code is working btw),

func NewAVLTree[T Comparable.Ordered[T]]() *AVLNode[T] {
    return nil
}

func NewAVLNode[T Comparable.Ordered[T]](key T) *AVLNode[T] {
    return &AVLNode[T]{Key: key, height: 1}
}

could be written as

func NewAVLTree[T X]() *AVLNode[T] {
    return nil
}

func NewAVLNode[T X](key T) *AVLNode[T] {
    return &AVLNode[T]{Key: key, height: 1}
}
0 Answers
Related