github.com/enetx/g@v1.0.80/examples/slices/slices_sort.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 "github.com/enetx/g" 7 "github.com/enetx/g/cmp" 8 ) 9 10 func main() { 11 type Order struct { 12 Product g.String 13 Customer g.String 14 Price g.Float 15 } 16 17 orders := g.Slice[Order]{ 18 {"foo", "alice", 1.00}, 19 {"bar", "bob", 3.00}, 20 {"baz", "carol", 4.00}, 21 {"foo", "alice", 2.00}, 22 {"bar", "carol", 1.00}, 23 {"foo", "bob", 4.00}, 24 } 25 26 // Sort by customer first, product second, and last by higher price 27 orders.SortBy(func(a, b Order) cmp.Ordering { 28 return a.Customer.Cmp(b.Customer). 29 Then(a.Product.Cmp(b.Product)). 30 Then(b.Price.Cmp(a.Price)) 31 }) 32 33 orders.Iter().ForEach(func(v Order) { 34 fmt.Printf("%s %s %.2f\n", v.Product, v.Customer, v.Price) 35 }) 36 37 // Output: 38 39 // foo alice 2.00 40 // foo alice 1.00 41 // bar bob 3.00 42 // foo bob 4.00 43 // bar carol 1.00 44 // baz carol 4.00 45 }