Trie Prefix Search And Autocomplete (Go)

Build a Go trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.

GoData Fetching

Code

snippet
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
}