Skip to content

Instantly share code, notes, and snippets.

@damienstanton
Created February 20, 2020 20:32
Show Gist options
  • Save damienstanton/57c8bb67f4837c754fd1a3a89c501618 to your computer and use it in GitHub Desktop.
Save damienstanton/57c8bb67f4837c754fd1a3a89c501618 to your computer and use it in GitHub Desktop.
Generics in Go (proposed)
/*
* This code is taken from Ian Lance Taylor's Gophercon 2019 talk on
* a proposed syntax/semantics for generics in Go. As such, it won't
* compile on any released Go compiler as of this posting (early 2020).
*/
// Tree is a generic binary tree
type Tree (type E) struct {
root *node(E)
compare func(E, E) int
}
type node (type E) struct {
val E
left, right *node(E)
}
// New creates a tree
func New (type E) (cmp func(E, E) int) *Tree(E) {
return &Tree(E){compare: cmp}
}
// Find an element in the tree
func (t *Tree(E)) Find(v E) bool {
return *t.find(e) != nil
}
// Insert a generic node into the tree
func (t *Tree(E)) Insert(v E) bool {
pn := t.find(v)
if *pn != nil {
return false
}
*pn = &node(E){val: v}
return true
}
func (t *Tree(E)) find(v E) **node(E) {
pn := &t.root
for *pn != nil {
switch cmp := t.compare(v, (*pn).val); {
case cmp < 0: pn = &(*pn).left
case cmp > 0: pn = &(*pn).right
default: return pn
}
}
return pn
}
func main() {
var intTree = tree.New(
func(a, b int) int { return a - b })
func InsertAndCheck(v int) {
intTree.Insert(v)
if !intTree.Find(v) {
log.Fatalf("%d not found after insertion", v)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment