Trie Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Trie runs in O(m) time and O(n*m) space, in Rust as in every other language.
- ✓std has no trie. The node is yours: std::collections::HashMap<char, Node> for sparse alphabets, std::collections::BTreeMap<char, Node> when you need sorted prefix enumeration for free, or [Option<Box<Node>>; 26] for a fixed lowercase alphabet.
- ✓Reviewers expect the iterative descent written as node = node.children.entry(ch).or_default(); the naive if let Some(n) = node.children.get_mut(&ch) inside a loop does not borrow-check, and reaching for Rc<RefCell<Node>> to escape that is the change request everyone writes.
- ✓The Rust trap: The trie's drop is recursive and the compiler generates it for you: dropping a node drops its HashMap, which drops each child node, which drops its HashMap.
- ✓HashMap's default hasher is SipHash-1-3, chosen for HashDoS resistance, and hashing a single char is almost entirely fixed setup cost, so per-edge hashing dominates a trie walk.
What Trie actually is
Trie in Rust: what you actually reach for
Rust implementation
use std::collections::HashMap;
#[derive(Default)]
pub struct Trie {
children: HashMap<char, Trie>,
is_word: bool,
}
impl Trie {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, word: &str) {
let mut node = self;
for ch in word.chars() {
// reborrow-and-reassign: the only shape the borrow checker accepts
node = node.children.entry(ch).or_default();
}
node.is_word = true;
}
fn walk(&self, prefix: &str) -> Option<&Trie> {
let mut node = self;
for ch in prefix.chars() {
node = node.children.get(&ch)?;
}
Some(node)
}
pub fn contains(&self, word: &str) -> bool {
matches!(self.walk(word), Some(n) if n.is_word)
}
pub fn with_prefix(&self, prefix: &str) -> Vec<String> {
let mut out = Vec::new();
let Some(start) = self.walk(prefix) else {
return out;
};
let mut stack = vec![(start, prefix.to_owned())];
while let Some((node, acc)) = stack.pop() {
if node.is_word {
out.push(acc.clone());
}
for (ch, child) in &node.children {
let mut next = acc.clone();
next.push(*ch);
stack.push((child, next));
}
}
out
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Trie?
std has no trie. The node is yours: std::collections::HashMap<char, Node> for sparse alphabets, std::collections::BTreeMap<char, Node> when you need sorted prefix enumeration for free, or [Option<Box<Node>>; 26] for a fixed lowercase alphabet. Recursive ownership works because HashMap boxes its table, so a plain struct Node { children: HashMap<char, Node>, is_word: bool } is legal without an explicit Box. Crates worth knowing: radix_trie and qp-trie for general maps, fst for a compiled immutable finite-state map with regex/fuzzy queries, and trie-rs for a LOUDS-succinct trie with common-prefix and incremental search. For the Aho-Corasick case named above, use the aho-corasick crate (BurntSushi) rather than building failure links onto a hand-rolled node.
What is the most common Rust mistake when implementing Trie?
The trie's drop is recursive and the compiler generates it for you: dropping a node drops its HashMap, which drops each child node, which drops its HashMap. On a deep trie built from long keys (paths, URLs, genome fragments) that is one stack frame per character and the process aborts with a stack overflow in the destructor, long after every test on short words passed. If keys can be long, write a manual Drop that pops children into a Vec worklist. Related trap: .chars() yields char (a 4-byte scalar), .bytes() yields u8, and mixing them across insert and lookup means a multi-byte key inserted one way is unreachable by the other.
How does Trie actually perform in Rust?
HashMap's default hasher is SipHash-1-3, chosen for HashDoS resistance, and hashing a single char is almost entirely fixed setup cost, so per-edge hashing dominates a trie walk. Swapping in rustc_hash::FxHashMap or ahash typically halves the descent. The HashMap variant allocates its table lazily on first insert, so interior nodes cost one heap allocation each and leaves cost none; the [Option<Box<Node>>; 26] variant is 208 bytes of pointer array (Option<Box<T>> is niche-optimised to 8 bytes) plus is_word, so 216 bytes per node whether it has one child or twenty-six, but it is a single indexed load with no hashing and no bounds check when the index is proven in range. Building the whole set into an fst removes both. Time complexity is O(m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.