golang 结构体数组 按字符串时间类型排序
时间: 2023-07-26 10:39:52 浏览: 68
可以使用 Go 语言中的 `sort` 包和 `time` 包来对结构体数组按字符串表示的时间排序。具体步骤如下:
1. 定义结构体,包含字符串表示的时间属性和其他属性。
```go
type MyStruct struct {
TimeStr string
// other fields
}
```
2. 定义结构体数组,并初始化。
```go
myStructs := []MyStruct {
{TimeStr: "2021-11-10 10:00:00", /* other fields */},
{TimeStr: "2021-11-11 09:00:00", /* other fields */},
// more elements
}
```
3. 定义排序函数,用于比较结构体的时间属性。
```go
func ByTime(s1, s2 *MyStruct) bool {
t1, _ := time.Parse("2006-01-02 15:04:05", s1.TimeStr)
t2, _ := time.Parse("2006-01-02 15:04:05", s2.TimeStr)
return t1.Before(t2)
}
```
4. 调用 `sort.Sort()` 函数,传入结构体数组和排序函数。
```go
sort.Slice(myStructs, func(i, j int) bool {
return ByTime(&myStructs[i], &myStructs[j])
})
```
这样,结构体数组 `myStructs` 就会按照字符串表示的时间属性从早到晚排序。需要注意的是,排序函数中的时间格式必须和字符串表示的时间格式匹配。在本例中,时间格式为 "2006-01-02 15:04:05",这是 Go 语言中的一个固定时间格式。如果时间格式不匹配,`time.Parse()` 函数将返回错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)