5

Golang不那么蛋疼的sort

 3 years ago
source link: https://jiajunhuang.com/articles/2020_01_07-golang_sort_slice.md.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Golang不那么蛋疼的sort

以前Go里写排序,如果不能用 sort.Ints, sort.Strings, sort.Float64s 等等快捷函数,就只能实现 sort.Interface 这个 接口了:

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 1.8以后,可以使用 sort.Slice 这个快捷函数快速实现排序而不用实现上面那个接口了,看例子:

package main

import (
	"fmt"
	"sort"
)

func main() {
	people := []struct {
		Name string
		Age  int
	}{
		{"Gopher", 7},
		{"Alice", 55},
		{"Vera", 24},
		{"Bob", 75},
	}
	sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
	fmt.Println("By name:", people)

	sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
	fmt.Println("By age:", people)
}

完美!比以前简单多了对不对。


参考资料:


微信公众号
关注公众号,获得及时更新

使用microk8s快速搭建k8s

Python中优雅的处理文件路径

Go语言MySQL时区问题

我的技术栈选型

为什么我要用Linux作为桌面?

disqus获取评论时忽略query string

MySQL性能优化指南

网络编程所需要熟悉的那些函数

DNSCrypt简明教程

SQLAlchemy简明教程

这些年,我们错过的n个亿

给Linux用户的FreeBSD快速指南

旧电脑也不能闲着:家用备份方案

将SQLite的数据迁移到MySQL

Linux托管Windows虚拟机最佳实践




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK