ModularM
Modular15mo ago
4 replies
Hammad Ali

Struct containing a list of itself?

Hi, I'm trying to creating a node-like tree which can contain a child (or children), but the mojo compiler doesn't really let me do that:
@value 
struct Node:
    var value: Int
    var children: List[Node]  # A list of Node objects

    fn __init__(inout self, value: Int):
        self.value = value
        self.children = List[Node]()  # Initialize an empty list

    fn add_child(inout self, child: Node):
        self.children.append(child)  # Add a child node to the list

fn main():
    var root = Node(1)
    var child1 = Node(2)
    var child2 = Node(3)

    root.add_child(child1)
    root.add_child(child2)

    print(root.value)  # Output: 1

error: function has recursive call to 'always_inline' function
struct Node:
^
Mojo/USL/shaderlab/libutils/utils_methods.mojo:87:8: note: through call here
/Users/ec2-user/actions-runner/_work/modular/modular/Kernels/mojo/stdlib/collections/list.mojo:186:8: note: to function marked 'always_inline' here
/Users/ec2-user/actions-runner/_work/modular/modular/Kernels/mojo/stdlib/memory/unsafe_pointer.mojo:413:9: note: call here recurses
Mojo/USL/shaderlab/libutils/utils_methods.mojo:87:8: note: back to function here
struct Node:
^
mojo: error: failed to run the pass manager
Was this page helpful?