golang 简单数组排序方法
可以使用 Go 语言中的 `sort` 包来对结构体数组按时间排序。具体步骤如下:
1. 定义结构体,包含时间属性和其他属性。
```go
type MyStruct struct {
Time time.Time
// other fields
}
```
2. 定义结构体数组,并初始化。
```go
myStructs := []MyStruct {
{Time: time.Now(), /* other fields */},
{Time: time.Now().Add(-time.Hour), /* other fields */},
// more elements
}
```
3. 定义排序函数,用于比较结构体的时间属性。
```go
func ByTime(s1, s2 *MyStruct) bool {
return s1.Time.Before(s2.Time)
}
```
4. 调用 `sort.Sort()` 函数,传入结构体数组和排序函数。
```go
sort.Slice(myStructs, func(i, j int) bool {
return ByTime(&myStructs[i], &myStructs[j])
})
```
这样,结构体数组 `myStructs` 就会按照时间属性从早到晚排序。