For sorting such struct I implemented three methods:
type Event struct {
timeEnd interface{}
size float64
}
func (s ByTime) Len() int {
return len(s)
}
func (s ByTime) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
Sometimes not all Events.timeEnd
are initialized and I want to put such Event
s into the back of slice and sorting them by size
field.
func (s ByTime) Less(i, j int) bool {
if s[i].timeEnd == nil || s[j].timeEnd == nil{
return s[i].size < s[j].size
}else {
return s[i].timeEnd.(float64) < s[j].timeEnd.(float64)
}
}
a, b, c, d := Event{timeEnd:12.}, Event{timeEnd:nil, size:-10}, Event{timeEnd:56.}, Event{timeEnd:nil, size:2}
queue := []*Event{}
queue = append(queue, &a, &b, &c, &d)
But as result I have:
[<nil> 12 56 <nil>]
While expecting [12 56 <nil> <nil>]
How to implement it correctly?
Here example in https://play.golang.org/p/FWU98npGtbU