2016-06-27 02:21:09 +00:00
|
|
|
// 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.
|
2015-03-06 16:10:34 +00:00
|
|
|
|
2015-03-06 00:29:16 +00:00
|
|
|
package examples
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/emirpasic/gods/sets/treeset"
|
|
|
|
)
|
|
|
|
|
2016-06-24 19:52:16 +00:00
|
|
|
// User model (id and name)
|
2015-03-06 00:29:16 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-24 19:52:16 +00:00
|
|
|
// CustomComparatorExample to demonstrate basic usage of CustomComparator
|
2015-03-07 16:09:47 +00:00
|
|
|
func CustomComparatorExample() {
|
2015-03-06 00:29:16 +00:00
|
|
|
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}
|
|
|
|
}
|