Go sort

104 阅读1分钟

前言

我这里直接和数据表一起使用

至于为什么不用数据库自带的排序,较为复杂的判断逻辑还是要自己写才行,这里只是简单的演示

package model

import (
   "backend/lib/mongo"
   "go.mongodb.org/mongo-driver/bson/primitive"
   "time"
)

type OtaAppSchema struct {
   Id          primitive.ObjectID `json:"_id" bson:"_id,omitempty"`
   App         string             `json:"app" bson:"app"`
   Logo        string             `json:"logo" bson:"logo"`               //logo
   Poster      string             `json:"poster" bson:"poster"`           // 封面
   Version     string             `json:"version" bson:"version"`         // app的字符串version
   VersionNum  int                `json:"versionNum" bson:"versionNum"`   // app的数组版本号
   PkgName     string             `json:"pkgName" bson:"pkgName"`         // 包名称
   Url         string             `json:"url" bson:"url"`                 // url
   Note        string             `json:"note" bson:"note"`               //  版本说明
   Description string             `json:"description" bson:"description"` // 描述,内部是用
   CreateTime  time.Time          `json:"create_time" bson:"create_time"` // 创建时间
   Icon        string             `json:"icon" bson:"icon"`               // app图标
   Size        int                `json:"size" bson:"size"`               //文件大小
   DownloadNum int                `json:"downloadNum" bson:"downloadNum"` // 下载次数
}

var OtaApp *mongo.Collection[OtaAppSchema]

func init() {
   // 创建collection
   OtaApp = register2Backend[OtaAppSchema]("ota_app")
}

type OtaAppSchemaSort []OtaAppSchema

//OtaAppSchemaSort 实现sort SDK 中的Interface接口

func (s OtaAppSchemaSort) Len() int {
   //返回传入数据的总数
   return len(s)
}
func (s OtaAppSchemaSort) Swap(i, j int) {
   //两个对象满足Less()则位置对换
   //表示执行交换数组中下标为i的数据和下标为j的数据
   s[i], s[j] = s[j], s[i]
}

func (s OtaAppSchemaSort) Less(i, j int) bool {
   //按字段比较大小,此处是降序排序
   //返回数组中下标为i的数据是否小于下标为j的数据
   return s[i].VersionNum > s[j].VersionNum
}

使用

otaAppList, err := model.OtaApp.Find(bson.M{"_id": bson.M{"$in": appIdlist}})
if err != nil {
   return nil
}
if len(otaAppList) > 1 {
   sort.Sort(model.OtaAppSchemaSort(otaAppList))
}
return otaAppList[0]