Skip to content

Instantly share code, notes, and snippets.

@lmas
Last active January 13, 2016 17:17
Show Gist options
  • Save lmas/3f39e5c05c7f3c2ad4c6 to your computer and use it in GitHub Desktop.
Save lmas/3f39e5c05c7f3c2ad4c6 to your computer and use it in GitHub Desktop.
Sort a Go struct based on a string value.
package main
import (
"fmt"
"sort"
)
// Our custom struct to sort.
type Data struct {
Name string
Desc string
}
// Shortcut type.
type DataSlice []*Data
// Len, Swap and Less is part of the sort interface we must supply.
func (d DataSlice) Len() int {
return len(d)
}
func (d DataSlice) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
func (d DataSlice) Less(i, j int) bool {
return d[i].Name < d[j].Name
}
// Some shortcut func for printing a slice.
func print_slice(d DataSlice) {
for i, v := range d {
fmt.Println(i, v)
}
}
func main() {
d := DataSlice{
&Data{"bbb", "desc of b"},
&Data{"ccc", "desc of c"},
&Data{"aaa", "desc of a"},
}
fmt.Println("Before sort:")
print_slice(d)
sort.Sort(d)
fmt.Println("\nAfter sort:")
print_slice(d)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment