简体   繁体   English

Golang如何在Generic中实现接口

[英]Golang how to implement Interface in Generic

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:我尝试学习 Go 通用,看看它是如何工作的,但我遇到了一些困惑的问题,如下所示: 我有一个通用定义如下:


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大家有什么想法,请提供一些线索提前谢谢

The method on MyTest only accept MyTest values as input while your interface specifies it must have "any" as input MyTest 上的方法仅接受 MyTest 值作为输入,而您的界面指定它必须具有“任何”作为输入

methods on types need to be identical to the ones defined by the interface to be used as the interface类型上的方法需要与要用作接口的接口定义的方法相同

@Pizza lord Thanks a lot, I fix the issue by changing like this: @Pizza lord 非常感谢,我通过这样的更改来解决这个问题:

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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM