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.")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?