I'm having a problem with sorting different arrays according to time in Go. I've read tutorial about how to sort it in relation to timeslices, but in the examples I've found it only takes into account the time itself, meaning any other data I sent with it will not be able to sort.
I'm my example I have a struct with an a date (time.Time) and an id (int) and I want to be able to sort all structs related to their dates in a shared list while still being able to access their ID.
I have three classes. Account: Adds Timestructs that keeps track of the instance date and id and adds it do the global list. Controller: Owns the global list and also takes care of calling the sorting functionality. TimeSlice: The default timeslice class with len,less and swap.
So to clarify, how do I sort the time in a way that I still can access other information about such as the ID of the Account?
//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)
}