How do I implement a generic hash table in Go?

A generic hash table implementation in Go can be achieved using a struct with type parameters. Below is a simple example of how you can create a generic hash table that allows for any data type as both keys and values.

package main import ( "fmt" "hash/fnv" ) // HashTable is a generic data structure type HashTable[K comparable, V any] struct { items map[K]V } // NewHashTable creates a new hash table func NewHashTable[K comparable, V any]() *HashTable[K, V] { return &HashTable[K, V]{items: make(map[K]V)} } // Put inserts a key-value pair into the hash table func (h *HashTable[K, V]) Put(key K, value V) { h.items[key] = value } // Get retrieves a value by key from the hash table func (h *HashTable[K, V]) Get(key K) (V, bool) { value, exists := h.items[key] return value, exists } // Remove deletes a key from the hash table func (h *HashTable[K, V]) Remove(key K) { delete(h.items, key) } func main() { hashTable := NewHashTable[string, int]() hashTable.Put("one", 1) hashTable.Put("two", 2) if value, exists := hashTable.Get("one"); exists { fmt.Println("Key 'one' found with value:", value) } hashTable.Remove("two") if _, exists := hashTable.Get("two"); !exists { fmt.Println("Key 'two' has been removed.") } }

Go Hash Table Generic Programming Data Structures Golang