mirror of
https://github.com/emirpasic/gods
synced 2024-11-06 15:20:25 +00:00
40 lines
638 B
Go
40 lines
638 B
Go
|
package examples
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"github.com/emirpasic/gods/sets/treeset"
|
||
|
)
|
||
|
|
||
|
type User struct {
|
||
|
id int
|
||
|
name string
|
||
|
}
|
||
|
|
||
|
// Comparator function (sort by IDs)
|
||
|
func byID(a, b interface{}) int {
|
||
|
|
||
|
// Type assertion, program will panic if this is not respected
|
||
|
c1 := a.(User)
|
||
|
c2 := b.(User)
|
||
|
|
||
|
switch {
|
||
|
case c1.id > c2.id:
|
||
|
return 1
|
||
|
case c1.id < c2.id:
|
||
|
return -1
|
||
|
default:
|
||
|
return 0
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func exampleCustomComparator() {
|
||
|
set := treeset.NewWith(byID)
|
||
|
|
||
|
set.Add(User{2, "Second"})
|
||
|
set.Add(User{3, "Third"})
|
||
|
set.Add(User{1, "First"})
|
||
|
set.Add(User{4, "Fourth"})
|
||
|
|
||
|
fmt.Println(set) // {1 First}, {2 Second}, {3 Third}, {4 Fourth}
|
||
|
}
|