0

I am trying to implement a Trie data structure in rust, here's the code with my questions in comments

#[derive(Default)]
pub struct Trie {
    is_word: bool,
    children: [Box<Option<Trie>>; 26],
}

impl Trie {
    pub fn new() -> Self {
        Trie::default()
    }

    pub fn insert(&mut self, word: &str) {
        let mut node = self;

        for ch in word.chars() {
            let idx = ch as usize - 'a' as usize;
            // Question: node.children[idx] is of type Box<Option<T>>, 
            // but why it can directly use Option API. Where does the deref() happen  
            node = node.children[idx].get_or_insert_with(|| Trie::new());
        }
        node.is_word = true;
    }

    pub fn contains(&self, word: &str) -> bool {
        let mut node = self;
        for ch in word.chars() {
            let idx = ch as usize - 'a' as usize;
            // Question: node.children[idx] is of type Box<Option<T>>,
            // but why it can directly use Option API. Where does the deref() happen
            match node.children[idx] {
                None => return false,
                Some(trie) => node = trie,
            }
        }
        node.is_word
    }
}

In two places I expect to play with a Box<Option> type but somehow the deref() is called somehow. I am using this to learn how to use box. There is a feature called implicit deref coercion but i think it has nothing to do with it

0 Answers0