0

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!

Shahriar
  • 13,460
  • 8
  • 78
  • 95
Junxi
  • 37
  • 1
  • 6

1 Answers1

1

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
    }
}
Anuruddha
  • 3,187
  • 5
  • 31
  • 47
  • It is really unobvious that even though `CompareTo` is declared on `node`, but that makes `Sortable` a pointer to `node`, not `node`. Which part of the language spec talks about this? – Sassa NF Dec 31 '18 at 09:54