gitee.com/quant1x/gox@v1.21.2/util/examples/customcomparator/customcomparator.go (about) 1 // Copyright (c) 2015, Emir Pasic. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "fmt" 9 "gitee.com/quant1x/gox/util/treeset" 10 ) 11 12 // User model (id and name) 13 type User struct { 14 id int 15 name string 16 } 17 18 // Comparator function (sort by IDs) 19 func byID(a, b interface{}) int { 20 21 // Type assertion, program will panic if this is not respected 22 c1 := a.(User) 23 c2 := b.(User) 24 25 switch { 26 case c1.id > c2.id: 27 return 1 28 case c1.id < c2.id: 29 return -1 30 default: 31 return 0 32 } 33 } 34 35 // CustomComparatorExample to demonstrate basic usage of CustomComparator 36 func main() { 37 set := treeset.NewWith(byID) 38 39 set.Add(User{2, "Second"}) 40 set.Add(User{3, "Third"}) 41 set.Add(User{1, "First"}) 42 set.Add(User{4, "Fourth"}) 43 44 fmt.Println(set) // {1 First}, {2 Second}, {3 Third}, {4 Fourth} 45 }