forked from emirpasic/gods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
customcomparator.go
45 lines (36 loc) · 901 Bytes
/
customcomparator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package examples
import (
"fmt"
"github.com/emirpasic/gods/sets/treeset"
)
// User model (id and name)
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
}
}
// CustomComparatorExample to demonstrate basic usage of CustomComparator
func CustomComparatorExample() {
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}
}