ByUploadTime(fMetaArray) 这个是什么意思呢,是将fmetaarray转换成Byuploadtime类型么

来源:2-5 编码实战:实现多个文件查询信息接口

愫暮灬

2020-02-03

ByUploadTime(fMetaArray) 这个是什么意思呢,是将fmetaarray转换成Byuploadtime类型么

写回答

2回答

xiaomo

2020-02-06

golang的标准库里关于排序sort定义了一个接口:

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)
}

那么我们只需要实现了Len, Less和Swap这三个方法的数据类型,相当于实现了sort接口,就能够调用sort.Sort()方法来进行排序了:

package meta

import "time"

const baseFormat = "2006-01-02 15:04:05"

type ByUploadTime []FileMeta

func (a ByUploadTime) Len() int {
	return len(a)
}

func (a ByUploadTime) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a ByUploadTime) Less(i, j int) bool {
	iTime, _ := time.Parse(baseFormat, a[i].UploadAt)
	jTime, _ := time.Parse(baseFormat, a[j].UploadAt)
	return iTime.UnixNano() > jTime.UnixNano()
}

这是自定义排序规则的一种实现方法。

1
1
愫暮灬
感谢老师!
2020-02-17
共1条回复

xiaomo

2020-02-06

同学你好,ByUploadTime的意思是对fMetaArray这个列表按元素中的uploadtime的先后来进行排序。

0
0

Go实战仿百度云盘-实现企业级分布式云存储系统

紧随“云时代”技术潮流,分布式云存储系统,做第一代云程序员

1077 学习 · 494 问题

查看课程