Cannot implicitly convert 'UnsafePointer[TrieNode, origin={}]'

Hi,

I just started to learn Mojo. I tried to implement Trie data structure, but I have a problem with my implementation. Following is the simple code:


struct TrieNode(Copyable, Movable, ExplicitlyCopyable):
    var children: List[Optional[UnsafePointer[TrieNode]]]
    var id: Int
    var char: Int

    fn __init__(out self):
        self.children = List[Optional[UnsafePointer[TrieNode]]]()
        for _ in range(256):
            self.children.append(None)
        self.id = 0
        self.char = 0


struct Trie(Copyable, Movable, ExplicitlyCopyable):
    var root: TrieNode

    fn __init__(out self):
        # Allocate memory for the root node and call its initializer.
        self.root = UnsafePointer[TrieNode].alloc(1)
        self.root.init_pointee_move(TrieNode())

And this is the error message:

(trie) (base) cahya@bintang:~/mojo/trie$ mojo trie_test.mojo                     
~/mojo/trie/trie_test.mojo:20:50: error: cannot implicitly convert 'UnsafePointer[TrieNode, origin={}]' value to 'TrieNode'
        self.root = UnsafePointer[TrieNode].alloc(1)
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
~/mojo/trie/trie_test.mojo:21:18: error: 'TrieNode' value has no attribute 'init_pointee_move'
        self.root.init_pointee_move(TrieNode())
        ~~~~~~~~~^
mojo: error: failed to parse the provided Mojo source module

Hi @cahya !
So this error message seems to be because self.root is of type TrieNode and the type returned from UnsafePionter[TrieNode].alloc(1) is an UnsafePointer[TrieNode] not a TriNode itself.

For cases like this, it’s actually best to use OwnedPointer or ArcPointer (if multi-threaded safety is a concern) to ensure the allocated data gets cleaned up at destruction.

For the root itself however, you shouldn’t even need to put it behind a pointer, you can just embed it in your struct directly!

struct Trie(...):
    var root: TrieNode

    fn __init__(out self):
        self.root = TrieNode()
1 Like

Thanks for the explanation