Sweet Jesus, Pooh! That's Not Honey! - You're Eating Recursion! - log_coffee!

submited by
Style Pass
2023-11-19 13:30:06

Most of the time, using Rust is just bliss. But today, it took us for a ride. We were reviewing some code (simplified for the blog) and stumbled upon a nested enum that looked like this

Assume Leaf is a placeholder to hold some data and thus the enum allows you to create a Rose tree. Now, we have a function create_nested_tree that accepts a single parameter depth as input and creates a flat Tree with depth depth and a Leaf at the end.

Initially, we immediately suspected the fmt::Debug hitting a recursive call and was causing the stack overflow. So, we removed the println! from main and included a println! in create_nested_tree before returning to value to isolate the issue. (What's a debugger?)

Note that the function create_nested_tree iteratively creates the nested Tree and there shouldn't be any concern of stack overflow.

There is no operation happening after returning the value and the code still stack overflows after the return. To debug, we created the MIR of our code and looked at create_nested_tree.

Leave a Comment