golang如何對自定義類型的slice進行排序?

golang如何對自定義類型的slice進行排序

引子

在golang的sort包裏,可以對int類型、float64類型和string類型這三種類型的slice排序。如果我們相對其他類型比如int64或者自定義類型的slice進行排序該如何做呢?

實現

其實在sort包裏,golang已經把排序使用的接口都已經定義好了。

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
	// Len is the number of elements in the collection.
	Len() int
	// Less reports whether the element with
	// index i should sort before the element with index j.
	Less(i, j int) bool
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

我們只需要對自定義類型或int64類型的slice實現上面的三個接口API即可。
然後就可以使用sort.Sort()或者sort.Stable()進行排序了。

代碼

type TimestampSlice []int64

func (a TimestampSlice) Len() int           { return len(a) }
func (a TimestampSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a TimestampSlice) Less(i, j int) bool { return a[i] < a[j] }

驗證

func main() {
	timestampSLice := TimestampSlice{9, 10, 8, 7, 4, 3, 5, 2, 6, 1}
	fmt.Println("before:", timestampSLice)
	sort.Sort(timestampSLice)
	//sort.Stable(timestampSLice)
	fmt.Println("after :", timestampSLice)
}

output:

before: [9 10 8 7 4 3 5 2 6 1]
after : [1 2 3 4 5 6 7 8 9 10]

小結

最近因爲項目需要。開始學習go,邊學邊用。真心覺得他簡潔、好用,還能看到很多包裏面的源代碼。源碼是第一手資料,比看任何文章都來的直接。爲go點贊!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章