I have a struct that has an task id, a date, and a comment field similar to this:
type Journal struct {
task_id int
date int
comment string
}
For each task_id, I was to create a list of all Journals for that task_id. Then I'd like to put each Journal List into a map so that I can easily manage each of my task id's. Here is some sample data:
100, 20140701, "Failed to complete"
100, 20140702, "Removed data and finished in 5 minutes"
120, 20140701, "No issues"
130, 20140701, "Called analyst"
130, 20140702, "reloaded data"
130, 20140703, "Emailed results"
For now I'm not sure if I need to order the comments beyond knowing which date they occurred.
How do I create the map of Lists? I haven't seen any examples where I "make" a list.
x := make(map[int]Journal)
You can create the map
you want with this code:
var m = make(map[int][]Journal)
for _, journal := range all_my_journals {
m[journal.task_id] = append(m[journal.task_id], journal)
}
Assuming all_my_journals
is a slice (or array) of all the Journal
variables you have.
Then, you can have a slice (and not a list) of all the Journal
s of a given id:
journals := m[my_task_id]
Adding to Julienc's excellent answer, if your intention is to be able to sort the journals, you could use a struct that implements sort.Interface like this:
type JournalSorter struct {
s []*Journal
f func(a, b *Journal) bool
rev bool
}
func NewSorter(j []*Journal) (js *JournalSorter) {
js = &JournalSorter{s: make([]*Journal, len(j))}
for i := range j {
js.s[i] = j[i]
}
return
}
func (js *JournalSorter) ById(reverse bool) []*Journal {
js.rev = reverse
js.f = js.byId
sort.Sort(js)
return js.s
}
func (js *JournalSorter) ByDate(reverse bool) []*Journal {
js.rev = reverse
js.f = js.byDate
sort.Sort(js)
return js.s
}
func (js *JournalSorter) byId(a, b *Journal) bool {
if js.rev {
return a.Id > b.Id
}
return a.Id < b.Id
}
func (js *JournalSorter) byDate(a, b *Journal) bool {
if js.rev {
return a.Date > b.Date
}
return a.Date < b.Date
}
func (js *JournalSorter) Len() int {
return len(js.s)
}
func (js *JournalSorter) Swap(i, j int) {
if js.s != nil && js.f != nil {
js.s[i], js.s[j] = js.s[j], js.s[i]
}
}
func (js *JournalSorter) Less(i, j int) bool {
if js.f != nil {
return js.f(js.s[i], js.s[j])
}
return false
}
///.................
func main() {
journals := m[my_task_id] //m = map[int][]*Journal
s1 := NewSorter(journals)
sorted_by_reverse_date := s1.ByDate(true)
}