2017-10-12 199 views
1

好吧,所以我對Go很新,我想讓自己熟悉按函數排序。我可能誤解了一些東西,所以如果我錯了,請糾正我。golang不能使用type作爲類型sort.Interface參數sort.Sort

我想創建一個Nodes的數組,其字段爲keyvalue。我想創建一個自定義的排序函數,按鍵排序節點數組。這是我迄今爲止的工作:

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

+1

Less方法的簽名是錯誤的。它應該採取兩個整數。請參閱[規範包示例](https://golang.org/pkg/sort/#example_)。 – Peter

+0

我應該如何修改它? – MrPyCharm

+1

請參閱[規範軟件包示例](https://golang.org/pkg/sort/#example_)。 – Peter

回答

3

這些函數使用集合索引,而不是集合中的元素。然後,您使用這些索引來索引ByKey數組 - 請參閱排序包中此interface的參考。

那麼你需要重寫你的函數來取int。你唯一需要改變的一個就是少功能,在你的情況下,它將使用鍵而不是僅僅說s [i] < s [j]你會說s [i] .key < s [j] 。鍵。下面是一個可運行的例子: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) 
} 

然而,在你的情況,因爲你只是想整理片,它可能是使用sort.Slice,忘了接口和一個單獨的片式更方便。您可以在一行代碼中進行排序。

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 }) 
相關問題