golang排序實現 sort介面實現

2021-09-02 06:27:01 字數 714 閱讀 4988

今天看見群裡再討論排序的sort.inte***ce的實現,有童鞋一直搞不定,我就上手了一下,哦耶搞定了,**放在這裡.

其實很簡單sort.inte***ce藉口有三個方法,給自己的struct實現這三個方法,然後用將自己的結構體傳給sort.sort方法就排序完成.

當然sort包也有幾個常用的方法sort.float64slice sort.intslise sort.stringslise,呵呵

package main

import (

"fmt"

"sort"

)

type mapsorter item

type item struct

func newmapsorter(m map[string]int64) mapsorter

return ms

}

func (ms mapsorter) len() int

func (ms mapsorter) less(i, j int) bool

func (ms mapsorter) swap(i, j int)

func main()

ms := newmapsorter(m)

sort.sort(ms)

for _, item := range ms

}

Golang使用sort介面實現排序

為實現對自定義的struct進行排序,可以呼叫sort包中的sort方法,為此,自定義的struct集合需要實現len less swap 三項方法。官方文件中的描述為 func sort data inte ce sort排序data。它呼叫1次data.len確定長度,呼叫o n log n 次...

golang基礎 排序sort

基本型別 int float64 string 的排序 int float64 string排序 intlist int float8list float64 stringlist string sort.ints intlist sort.float64s float8list sort.stri...

golang 使用 sort 來排序

golang sort package sort 操作的物件通常是乙個 slice,需要滿足三個基本的介面,並且能夠使用整數來索引 a type,typically a collection,that satisfies sort.inte ce can be sorted by the routi...