Skip to content

Instantly share code, notes, and snippets.

@SteveBate
Created September 22, 2015 10:41
Show Gist options
  • Save SteveBate/c788a65415d77fd6623f to your computer and use it in GitHub Desktop.
Save SteveBate/c788a65415d77fd6623f to your computer and use it in GitHub Desktop.
Sorting in Go using the built in interface methods on a user defined type
package main
import (
"fmt"
"sort"
"time"
)
type Event struct {
Description string
Date time.Time
Kind string
}
type ByDate []Event
func (b ByDate) Len() int { return len(b) }
func (b ByDate) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByDate) Less(i, j int) bool { return b[i].Date.Hour() < b[j].Date.Hour() }
type ByDescription []Event
func (b ByDescription) Len() int { return len(b) }
func (b ByDescription) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByDescription) Less(i, j int) bool { return b[i].Description < b[j].Description }
type ByKind []Event
func (b ByKind) Len() int { return len(b) }
func (b ByKind) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByKind) Less(i, j int) bool { return b[i].Kind < b[j].Kind }
func main() {
events := make([]Event, 0, 3)
events = append(events, Event{"DELIVERED", time.Now().Add(3 * time.Hour), "PROCESSED"})
events = append(events, Event{"SCANNED AT DEPOT", time.Now().Add(1 * time.Hour), "SCAN"})
events = append(events, Event{"ON VAN", time.Now().Add(2 * time.Hour), "SCAN"})
sort.Sort(ByKind(events))
for i, _ := range events {
fmt.Printf("%20s - %40v\n", events[i].Description, events[i].Date)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment