golang排序自定义类型(结构体)

golang排序自定义类型

我们需要用到go自带的标准库标sort包

sort包提供了排序切片和用户自定义数据集以及相关功能的函数

sort包主要针对[]int[]float64[]string,以及其他自定义切片的排序

结构体

type IntSlice struct
type Float64Slice
type StringSlice

一些函数

image-20230118185036583

接口 type Interface

自定义的接口如果需要排序以下三个接口

type MyInterface interface {
    
    
  Len() int // Len方法返回集合中的元素个数
  Less(i, j int) bool // i > j,该方法返回索引i的元素是否比索引j的元素小
  Swap(i, j int) // 交换i,j的值
}

举个例子

排序自定义类型

主要需要实现三个方法

package main

import (
	"fmt"
	"sort"
)

func main() {
    
    
	// 产生几个对象
	b1 := Person{
    
    age: 18, name: "张三"}
	b2 := Person{
    
    age: 14, name: "李四"}
	b3 := Person{
    
    age: 20, name: "王五"}
	pArray := []Person{
    
    b1, b2, b3}
	// 排序
	sort.Sort(PersonArray(pArray))
	fmt.Println(pArray) // [{14 李四} {18 张三} {20 王五}]
}

type PersonArray []Person

type Person struct {
    
    
	age  int
	name string
}

// Len 实现Len方法,返回长度
func (b PersonArray) Len() int {
    
    
	return len(b)
}

// Less 判断指定索引的两个数字的大小
func (b PersonArray) Less(i, j int) bool {
    
    
	fmt.Println(i, j, b[i].age < b[j].age, b)
	return b[i].age < b[j].age
}

// Swap 交换两个索引位置的值
func (b PersonArray) Swap(i, j int) {
    
    
	b[i], b[j] = b[j], b[i]
}

猜你喜欢

转载自blog.csdn.net/fengxiandada/article/details/128731186