Need help for "reached the recursion limit while instantiating..."

I got "reached the recursion limit ..." error for the following code. Please help.

enum Node<Item> {
    Leaf(Item),
    Children(Vec<Node<Item>>),
}

impl<It> Node<It> {
    fn traverse(&self, f: impl Fn(&It)) {
        match self {
            Node::Leaf(item) => {
                f(item);
            }
            Node::Children(children) => {
                for node in children {
                    node.traverse(&f);
                }
            }
        }
    }
}

fn main() {
    let tree = Node::Children(vec![
        Node::Leaf(5),
        Node::Leaf(4),
        Node::Children(vec![Node::Leaf(3), Node::Leaf(2), Node::Children(vec![])]),
        Node::Children(vec![Node::Children(vec![
            Node::Children(vec![Node::Leaf(1)]),
            Node::Leaf(0),
        ])]),
    ]);
    tree.traverse(|x| println!("{x}"))
}
2 Likes

Say you pass a closure of type T to traverse, then node.traverse(&f) will codegen traverse with &T as closure, and this one then codegens &&T and so on. The fix would be to take f: &impl Fn(&It) as argument and use node.traverse(f). Note how the & moved from the call to the parameter type.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.