Home > Blockchain >  Golang how to implement Interface in Generic
Golang how to implement Interface in Generic

Time:08-20

I try to learn Go generic, to see how it works but I got some confused issues as below: I have a generic definition as below:


type Interface interface {
    Less(d any) bool
}
type DLinkedList[T Interface] struct {
    
    head *Node[T]
    tail *Node[T]
}

type Node[T Interface] struct {
    prev *Node[T]
    next *Node[T]
    val  T
}

func (dl *DLinkedList[T]) Insert(val ...T) {
    if dl.head == nil {
        dl.head = &Node[T]{val: val[0]}
        dl.tail = dl.head
        val = val[1:]
    }
    for _, val := range val {
        dl.tail.next = &Node[T]{val: val}
        dl.tail.next.prev = dl.tail
        dl.tail = dl.tail.next
    }
}
func (dl *DLinkedList[T]) Sort() {
    front := dl.head
    var back *Node[T] = nil
    for front != nil {
        back = front.next
        for back != nil && back.prev != nil && back.val.Less(back.prev.val) {
            back = back.prev
        }
        front = front.next
    }
}

Now use my generic as below:

type MyTest struct {
    Name string
    Age  int
}

func (this MyTest) Less(d MyTest) bool  { return this.Age < d.Age }

func main() {

    dl := DLinkedList[MyTest]{}

    dl.Insert(MyTest{Name: "yx", Age: 12})

    
}

But build failed, error :

MyTest does not implement Interface (wrong type for Less method)
                have Less(d MyTest) bool
                want Less(d any) bool

So the problem is any type can not accept my Struct. what am I missing? any ideas you guys , please give some clues thanks in advance

CodePudding user response:

The method on MyTest only accept MyTest values as input while your interface specifies it must have "any" as input

methods on types need to be identical to the ones defined by the interface to be used as the interface

CodePudding user response:

@Pizza lord Thanks a lot, I fix the issue by changing like this:

From:

func (this MyTest) Less(d MyTest) bool  { return this.Age < d.Age }

TO:

func (this MyTest) Less(d any) bool  { return this.Age < d.(MyTest).Age }
  • Related