Skip to content

Instantly share code, notes, and snippets.

@jriegner
Last active January 8, 2019 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jriegner/feaa165c9e4e0f898b1814101d66317d to your computer and use it in GitHub Desktop.
Save jriegner/feaa165c9e4e0f898b1814101d66317d to your computer and use it in GitHub Desktop.
sort a slice by weight descending
package main
import (
"fmt"
"sort"
)
type node struct {
weight int
}
func main() {
var nodes []node
n1 := node{weight: 0}
n2 := node{weight: 0}
n3 := node{weight: 326}
n4 := node{weight: 4}
nodes = append(nodes, n1)
nodes = append(nodes, n2)
nodes = append(nodes, n3)
nodes = append(nodes, n4)
fmt.Println(nodes)
sort.Slice(nodes, func(j, k int) bool { return nodes[j].weight > nodes[k].weight })
fmt.Println(nodes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment