Hi,
I am trying to implement a tree-like automata structure. It accepts vectors of chars, and accumulates them to store strings in the leaf node. So, for example, after I store a data like this diagram,
'a' -- 'b' -- ('a': "the_value1")
\ \
\ -- ('c': "the_value3")
\
------('c': "the_value2")
I query 'a' -> 'b' -> 'c', and I will get "the_value3."
I am a totally newbie for rust. So first I tried C-like iteration. But even in constructing the tree, I met tons of the lifetime hell... I cannot store pointers to point the current node. After meeting tons of compilation error, I cannot even figure out what can I do more..T.T
use std::collections::BTreeMap;
#[derive(Clone)]
pub enum Node {
Internal { children: BTreeMap<char, Box<Node>> },
Leaf(String)
}
pub struct Tree {
head: Node,
}
impl Tree {
pub fn new() -> Tree {
Tree {
head: Node::Internal { children: BTreeMap::new() }
}
}
pub fn add(&mut self, name: String, keys: Vec<char>) {
let mut cur = &mut self.head;
for (i, key) in keys.iter().enumerate() {
let mut next = if let Node::Internal { children: ref mut children } = *cur {
if let Some(&mut ref n) = children.get_mut(&key) {
if i == keys.len() - 1 {
// Leaf node is already occupied.
panic!("Internal Error.");
}
&mut n
} else {
let mut node: &mut Node = if i == keys.len() - 1 {
&mut Node::Leaf(name.clone())
} else {
&mut Node::Internal { children: BTreeMap::new() }
};
children.insert(*key, Box::new(node.clone()));
children.get_mut(&key).unwrap()
}
} else {
// Leaf node cannot has children. so this must be exception.
panic!("Internal Error.")
};
cur = next;
}
}
}
fn main() {
let mut tree = Tree::new();
tree.add(String::from("the_value1"), vec!['a', 'b', 'a']);
tree.add(String::from("the_value2"), vec!['a', 'c']);
tree.add(String::from("the_value3"), vec!['a', 'b', 'c']);
}
Can I have some hint? Sorry for stealing your time!