How to Implement Hash Table in Go: Simple Guide with Example
In Go, you can implement a hash table using the built-in
map type, which stores key-value pairs with fast lookup. You define a map with make(map[keyType]valueType) and use keys to store and retrieve values efficiently.Syntax
The basic syntax to create a hash table in Go uses the map keyword. You declare a map with key and value types inside square brackets and curly braces. Use make to initialize it before use.
map[keyType]valueType: Defines the map type.make(map[keyType]valueType): Creates an empty map.- Use
map[key] = valueto add or update entries. - Use
value := map[key]to retrieve values.
go
var hashTable map[string]int hashTable = make(map[string]int) hashTable["apple"] = 5 value := hashTable["apple"]
Example
This example shows how to create a hash table to count word occurrences in a slice of strings. It demonstrates adding, updating, and retrieving values from the map.
go
package main import "fmt" func main() { words := []string{"apple", "banana", "apple", "orange", "banana", "apple"} wordCount := make(map[string]int) for _, word := range words { wordCount[word]++ } fmt.Println("Word counts:") for word, count := range wordCount { fmt.Printf("%s: %d\n", word, count) } }
Output
Word counts:
apple: 3
banana: 2
orange: 1
Common Pitfalls
Common mistakes when using hash tables (maps) in Go include:
- Not initializing the map with
makebefore use, causing runtime panic. - Accessing a key that does not exist returns the zero value of the value type, which can be confusing.
- Maps are not safe for concurrent use without synchronization.
Always check if a key exists using the two-value assignment to avoid confusion.
go
package main import "fmt" func main() { var m map[string]int // m["key"] = 1 // This causes panic: assignment to entry in nil map m = make(map[string]int) m["key"] = 1 // Correct initialization value, ok := m["missing"] fmt.Println("Value:", value, "Exists:", ok) // Value: 0 Exists: false }
Output
Value: 0 Exists: false
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Create map | make(map[keyType]valueType) | Initialize an empty hash table |
| Add/update | map[key] = value | Set value for a key |
| Retrieve | value := map[key] | Get value for a key (zero value if missing) |
| Check existence | value, ok := map[key] | Check if key exists |
| Delete key | delete(map, key) | Remove key from map |
Key Takeaways
Use Go's built-in map type to implement hash tables easily and efficiently.
Always initialize maps with make before adding entries to avoid runtime errors.
Check if a key exists using the two-value assignment to handle missing keys safely.
Maps are not safe for concurrent use without extra synchronization.
Use delete to remove keys from the map when needed.