Ahmed Dhanani
Ahmed Dhanani

Reputation: 861

golang cannot use type as type sort.Interface in argument to sort.Sort

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

Upvotes: 1

Views: 3482

Answers (1)

Kenny Grant
Kenny Grant

Reputation: 9623

These functions take collection indexes, not elements from the collection. You then use those indexes to index into the ByKey array - see the reference for this interface in the sort package.

So then you need to rewrite your functions to take int. The only one you need to change typically is the less function, which in your case will use the key rather than just saying s[i] < s[j] you'd be saying s[i].key < s[j].key. Here is a runnable example: play.golang.org

type ByKey []Node

func (s ByKey) Len() int           { return len(s) }
func (s ByKey) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s ByKey) Less(i, j int) bool { return s[i].key < s[j].key }

func main() {

    nodes := []Node{
        {key: 2, value: 200},
        {key: 1, value: 100},
        {key: 3, value: 50},
    }

    sort.Sort(ByKey(nodes))
    fmt.Println(nodes)
}

However, in your case since you just want to sort a slice, it might be more convenient to use sort.Slice and forget about the interface and a separate slice type. You can do the sorting then in one line of code in place.

nodes := []Node{
        {key: 2, value: 200},
        {key: 1, value: 100},
        {key: 3, value: 50},
    }

sort.Slice(nodes, func(i, j int) bool { return nodes[i].key < nodes[j].key })

Upvotes: 4

Related Questions