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

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