我在Go中根据时间排序不同的数组有问题。我已经阅读了有关如何根据时间片对其进行排序的教程,但在示例中,我发现它只考虑了时间本身,这意味着我发送的任何其他数据都无法排序。
我的示例我有一个带有日期(time.Time)和id(int)的结构,我希望能够在共享列表中对与日期相关的所有结构进行排序能够访问他们的ID。
我有三节课。 帐户:添加跟踪实例日期和ID的Timestructs,并添加它来执行全局列表。 控制器:拥有全局列表,并负责调用排序功能。 TimeSlice:默认的timeslice类,len,less和swap。
因此,为了澄清,我如何以一种我仍然可以访问其他信息(例如帐户ID)的方式对时间进行排序?
//Account.go
func (i *InstanceController) InitAccount() *Account {
account := new(Account)
i.IncrementIDs(account) //Sets account id
t := TimeStruct{date: account.Created, id: account.ID}
i.AccountStamps[account.ID] = t
}
//Controller.go
type InstanceController struct {
AccountList map[int]*Account
ID int
AccountStamps map[int]TimeStruct
}
func InitInstanceController() *InstanceController {
ic := new(InstanceController)
ic.ID = 0
ic.AccountList = make(map[int]*Account)
ic.AccountStamps = make(map[int]*TimeStruct)
return ic
}
//TimeSlice.go
package account
import "fmt"
import "time"
import "sort"
type timeSlice []time.Time
func (s timeSlice) Less(i, j int) bool { return s[i].Before(s[j]) }
func (s timeSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s timeSlice) Len() int { return len(s) }
var past = time.Date(2010, time.May, 18, 23, 0, 0, 0, time.Now().Location())
var present = time.Now()
var future = time.Now().Add(24 * time.Hour)
var dateSlice timeSlice = []time.Time{present, future, past}
func funcers() {
fmt.Println("Past : ", past)
fmt.Println("Present : ", present)
fmt.Println("Future : ", future)
fmt.Println("Before sorting : ", dateSlice)
sort.Sort(dateSlice)
fmt.Println("After sorting : ", dateSlice)
sort.Sort(sort.Reverse(dateSlice))
fmt.Println("After REVERSE sorting : ", dateSlice)
}
func SortTimeSlice(t timeSlice) {
fmt.Println("Before sorting : ", t)
sort.Sort(t)
fmt.Println("After sorting : ", t)
}
type TimeStruct struct {
date time.Time
id int
}
func (ic *InstanceController) AddTimeStruct(t TimeStruct) {
ic.AccountStamps[t.id] = t
}
func (ic *InstanceController) AppendToListForSort(ts []TimeStruct) {
newList := []time.Time{}
for k, v := range ts {
newList = append(v.date)
}
sort.Sort(newList)
}