Trie Prefix Search And Autocomplete (Rust)

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

RustData Fetching

Code

rustsnippet
14 lines
use std::collections::HashMap;

struct TrieNode { children: HashMap<char, Box<TrieNode>>, is_word: bool, freq: i32 }
impl Default for TrieNode { fn default() -> Self { Self { children: HashMap::new(), is_word: false, freq: 0 } } }

struct Trie { root: Box<TrieNode> }
impl Trie {
    fn new() -> Self { Self { root: Box::new(TrieNode::default()) } }
    fn insert(&mut self, word: &str, freq: i32) {
        let mut node = &mut self.root;
        for ch in word.chars() { node = node.children.entry(ch).or_default(); }
        node.is_word = true; node.freq += freq;
    }
}

How the snippet works

The working surface is the functions default, new and insert — everything else is wiring.

Repetition is confined to for ch in word.chars() { node = node.children.entry(ch).or_default(); } — the rest of the file is straight-line.

Applying it

Entry signature: fn default() -> Self

default is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

impl Default for TrieNode { fn default() -> Self { Self { children: HashMap::new(), is_word: false, freq: 0 } } }
fn new() -> Self { Self { root: Box::new(TrieNode::default()) } }
fn insert(&mut self, word: &str, freq: i32) {
let mut node = &mut self.root;
for ch in word.chars() { node = node.children.entry(ch).or_default(); }
node.is_word = true; node.freq += freq;
}

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `std::collections`. The file defines `default`, `new`, `insert` at load time.