golang 实现自定义结构的排序

    先说明下是什么场景:业务需要对所有的请求参数按照key的大小进行排序然后将其拼成一个字符串,说到这里大家可能就明白其实这就是一个验证请求签名的东西。那在php中对key-value结构按照key来排序直接使用ksort函数就可以了,但是在go中并没有给定这样的方法,需要自己来实现。

事实上,在go的sort包中,只提供了几种最简单的数据类型的排序,分别是int  string float64类型的slice,可以说,基本上所有的排序都需要工程师自己来扩展,好在,在go中扩展这样的排序方法很简单。

    先来看看sort包源码是怎么做的:

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. 
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)
}

在源码go/src/sort/sort.go里,根据注释可以清晰的看到sort包定义了一个interface类型sort.Interface, 只要是实现了Len, Less和Swap三种方法的数据类型就能够直接调用sort.Sort()方法进行排序。而不需要关心sort内部究竟用哪种算法实现了排序。

再细致的看一下,sort包内部实现了四种排序算法,插入,归并,堆排序和快速排序。这三种方法都是私有的,在程序调用Sort()函数时,该函数会根据输入的情况动态决定使用何种排序算法,即sort包向我们隐藏了排序具体的实现方式。感兴趣的同学可以看一下Sort()函数是如何做的。

接下来就看下如何对一个map结构根据key来进行排序:

//map排序,按key排序
type MapSorter []MapItem

func NewMapSorter(m map[string]string) MapSorter {
        ms := make(MapSorter, 0, len(m))
        for k, v := range m { 
                ms = append(ms, MapItem{Key: k, Val: v}) 
        }   

        return ms
}                                                                                                                                                                                                                                                                             

type MapItem struct {
        Key string
        Val string
}

func (ms MapSorter) Len() int {
        return len(ms)
}

func (ms MapSorter) Swap(i, j int) {
        ms[i], ms[j] = ms[j], ms[i]
}

//按键排序
func (ms MapSorter) Less(i, j int) bool {
        return ms[i].Key < ms[j].Key
}

 

主要思路就是定义一个struct,它的两个属性分别对应于map的key/value,Less函数中对key值进行大小对比。相信看一下上面的代码,大家就能明白这段代码该如何写。。。

 

转载于:https://my.oschina.net/u/3470972/blog/1583854

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值