Last active
August 29, 2015 14:07
-
-
Save angch/0969baefedcd8d7a1c53 to your computer and use it in GitHub Desktop.
golang: Just a quick test of a using github.com/google/btree using mixed types: string and int
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Just a quick test of a using github.com/google/btree using | |
// mixed types (string) and (int) | |
package main | |
import ( | |
"fmt" | |
"github.com/google/btree" | |
"strconv" | |
) | |
type myString string | |
// There ought to be a better way | |
func (a myString) Less(b btree.Item) bool { | |
switch b.(type) { | |
case myString: | |
return a < b.(myString) | |
case Int: | |
return string(a) < strconv.Itoa(int(b.(Int))) | |
} | |
return true | |
// If we don't have type mixing/assertions, we'd just do a: | |
return a < b.(myString) | |
} | |
func (s myString) String() string { | |
return string(s) | |
} | |
type Int int | |
// There ought to be a better way | |
func (a Int) Less(b btree.Item) bool { | |
switch b.(type) { | |
case myString: | |
return strconv.Itoa(int(a)) < string(b.(myString)) | |
case Int: | |
return a < b.(Int) | |
} | |
return true | |
} | |
func main() { | |
tree := btree.New(8) | |
tree.ReplaceOrInsert(myString("Hello")) | |
tree.ReplaceOrInsert(myString("World")) | |
tree.ReplaceOrInsert(Int(42)) | |
tree.ReplaceOrInsert(myString("Happy")) | |
tree.ReplaceOrInsert(myString("New")) | |
tree.ReplaceOrInsert(myString("Year")) | |
tree.ReplaceOrInsert(Int(2014)) | |
tree.ReplaceOrInsert(myString("1984 is a book")) | |
// A bit silly, but we don't have non destructive reads on | |
// trees in github.com/google/btree, unlike github.com/petar/gollrb | |
for item := tree.DeleteMin(); item != nil; item = tree.DeleteMin() { | |
fmt.Println(item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment