Skip to content

Instantly share code, notes, and snippets.

@ARolek
Created July 2, 2014 20:27
Show Gist options
  • Save ARolek/86a625f70d284827559f to your computer and use it in GitHub Desktop.
Save ARolek/86a625f70d284827559f to your computer and use it in GitHub Desktop.
Sorting structs in GoLang
package main
import "fmt"
import "sort"
type Color struct {
Area float64
}
type ByArea []Color
func (c ByArea) Len() int { return len(c) }
func (c ByArea) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c ByArea) Less(i, j int) bool { return c[i].Area > c[j].Area }
func main() {
var colors = []Color{
{1.0},
{0.5},
{0.9},
{0.1},
}
// before sort
fmt.Println(colors)
sort.Sort(ByArea(colors))
// after sort
fmt.Println(colors)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment