1
好吧,所以我對Go很新,我想讓自己熟悉按函數排序。我可能誤解了一些東西,所以如果我錯了,請糾正我。golang不能使用type作爲類型sort.Interface參數sort.Sort
我想創建一個Nodes
的數組,其字段爲key
和value
。我想創建一個自定義的排序函數,按鍵排序節點數組。這是我迄今爲止的工作:
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)
}
,但我一直在這裏,我呼籲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
我不知道這是什麼錯誤是試圖傳達。任何幫助,將不勝感激。 TIA
Less方法的簽名是錯誤的。它應該採取兩個整數。請參閱[規範包示例](https://golang.org/pkg/sort/#example_)。 – Peter
我應該如何修改它? – MrPyCharm
請參閱[規範軟件包示例](https://golang.org/pkg/sort/#example_)。 – Peter