How do I implement a generic binary search tree in Go?

A generic binary search tree (BST) can be implemented in Go using Go's type parameters introduced in version 1.18. Below is an example of a generic binary search tree that supports inserting and searching for values.

package main import ( "fmt" ) // Node represents a node in the binary search tree type Node[T comparable] struct { value T left *Node[T] right *Node[T] } // BST represents the binary search tree type BST[T comparable] struct { root *Node[T] } // Insert adds a value to the BST func (b *BST[T]) Insert(value T) { b.root = insert(b.root, value) } func insert[T comparable](node *Node[T], value T) *Node[T] { if node == nil { return &Node[T]{value: value} } if value < node.value { node.left = insert(node.left, value) } else { node.right = insert(node.right, value) } return node } // Search checks if a value exists in the BST func (b *BST[T]) Search(value T) bool { return search(b.root, value) } func search[T comparable](node *Node[T], value T) bool { if node == nil { return false } if value == node.value { return true } else if value < node.value { return search(node.left, value) } else { return search(node.right, value) } } func main() { tree := &BST[int]{} tree.Insert(5) tree.Insert(3) tree.Insert(7) fmt.Println(tree.Search(3)) // true fmt.Println(tree.Search(6)) // false }

Go Generic Binary Search Tree BST Go Generics