Trie Prefix Search And Autocomplete (Go)
Build a Go trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.
Code
package main
type TrieNode struct {
children map[byte]*TrieNode
isWord bool
freq int
}
func newTrieNode() *TrieNode { return &TrieNode{children: make(map[byte]*TrieNode)} }
type Trie struct{ root *TrieNode }
func (t *Trie) Insert(word string, freq int) {
node := t.root
for i := 0; i < len(word); i++ {
ch := word[i]
if node.children[ch] == nil { node.children[ch] = newTrieNode() }
node = node.children[ch]
}
node.isWord = true
node.freq += freq
}Inside the snippet
Trie Prefix Search And Autocomplete (Go) is built around the functions newTrieNode and Insert.
Iteration happens inside for i := 0; i < len(word); i++ — everything outside it runs once.
Putting it to use
The primary signature is func (t *Trie) Insert(word string, freq int)
Insert hangs off Trie: obtain an instance and invoke the method on it.
Core lines
func newTrieNode() *TrieNode { return &TrieNode{children: make(map[byte]*TrieNode)} }
func (t *Trie) Insert(word string, freq int) {
node := t.root
for i := 0; i < len(word); i++ {
ch := word[i]
if node.children[ch] == nil { node.children[ch] = newTrieNode() }
node = node.children[ch]
}
node.isWord = true
node.freq += freq
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `newTrieNode`, `Insert` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.