简体   繁体   中英

Golang struct pointer invokes interface method

I'm picking up Golang and I've got a problem in traversing a linked list. What I intend to do is visit all nodes of the linked list, and call an interface method from each node.

I've defined an interface

type Sortable interface {
    CompareTo(t Sortable) int
}

I've defined a node type and a linked list

type node struct {
    pNext *node
    value int
}

type LinkedList struct {
    PHead, PNode *node
}

func (n node) CompreTo(t Sortable) int{
    other := t.(node)
    if n.value == other.value {
        return 0
    } else if n.value > other.value {
        return 1
    } else {
        return -1
    }
}

The problem occurs when I'm doing a comparison while traversing the linked list: ......

PNode.CompareTo(PNode.pNext)

and I get: panic: interface conversion: Sortable is *node, not node

Guess this is because PNode and PNode.pNext are pointers to the node struct, not node objects? Then how should I cast the pointer to make it right? I used to write in C++ so maybe my strategy goes wrong in Golang world?

Any advice is appreciated!

You have to assert the Sortable t to a pointer node.

func (n node) CompreTo(t Sortable) int{
    other := t.(*node)
    if n.value == other.value {
        return 0
    } else if n.value > other.value {
        return 1
    } else {
        return -1
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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