This is a very simple example, but how would I do something similar to:
let fact = |x: u32| {
match x {
0 => 1,
_ => x * fact(x - 1),
}
};
I know that this specific example can be easily done with iteration, but I'm wondering if it's possible to make a recursive function in Rust for more complicated things (such as traversing trees) or if I'm required to use my own stack instead.
There are a few ways to do this.
You can put closures into a struct and pass this struct to the closure. You can even define structs inline in a function:
This gets around the problem of having an infinite type (a function that takes itself as an argument) and the problem that
fact
isn't yet defined inside the closure itself when one writeslet fact = |x| {...}
and so one can't refer to it there.This works in Rust 1.17, but may possibly be made illegal in the future since it's dangerous in some instances, as outlined in the blog post The Case of the Recurring Closure. It's entirely safe here since there is no mutation though.
Another option is to just write a recursive function as a
fn
item, which can also be defined inline in a function:This works fine if you don't need to capture anything from the environment.
One more option is to use the
fn
item solution but explicitly pass the args/environment you want.All of these work with Rust 1.17 and have probably worked since version 0.6. The
fn
's defined insidefn
s are no different to those defined at the top level, except they are only accessible within thefn
they are defined inside.