Created
July 2, 2014 20:27
-
-
Save ARolek/86a625f70d284827559f to your computer and use it in GitHub Desktop.
Sorting structs in GoLang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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