Okay, so I am very new to Go and i am trying to get myself familiar with sorting by functions. I might have misunderstood something, so please correct me if i'm wrong.
I am trying to create an array of Nodes
with fields key
and value
. I would like to create a custom sorting function that sorts the array of nodes by their keys. Here's my working so far:
package main
import (
"sort"
"fmt"
)
type Node struct {
key, value int
}
type ByKey []Node
func (s ByKey) Len() int {
return len(s)
}
func (s ByKey) Swap(i, j Node) {
temp := Node{key: i.key, value : i.value}
i.key, i.value = j.key, j.value
j.key, j.value = temp.key, temp.value
}
func (s ByKey) Less(i, j Node) bool {
return i.key < j.key
}
func main(){
nodes := []Node{
{ key : 1, value : 100 },
{ key : 2, value : 200 },
{ key : 3, value : 50 },
}
sort.Sort(ByKey(nodes))
fmt.Println(nodes)
}
But I keep getting this error at the line where I am calling Sort
:
cannot use ByKey(nodes) (type ByKey) as type sort.Interface in argument to sort.Sort:
ByKey does not implement sort.Interface (wrong type for Less method)
have Less(Node, Node) bool
want Less(int, int) bool
I am not sure what this error is trying to convey. Any help would be appreciated. TIA