Can you create a recursive closure in Rust?
Hi everyone! I'm learning Rust and trying to write a recursive closure to compute factorial. Here's my code:
```rust
let factorial = |n: u32| -> u32 {
if n <= 1 {
1
} else {
n * factorial(n - 1) // error: cannot capture `factorial` in its own initializer
}
};
```
The compiler gives an error: "cannot capture `factorial` in its own initializer". I understand that a closure cannot capture a variable that hasn't been fully initialized yet. But how do you make a recursive closure then?
I tried declaring `factorial` as `let factorial: Box u32>`, but that didn't help. I know I can use a regular function `fn factorial(n: u32) -> u32`, but I need a closure specifically because I want to capture external variables.
Please advise on how to
No answers yet.
Log in to leave an answer
Blogs
How to Get a Job as a Java Developer: Tips and Resume
Telegram bot in Go: from idea to deployment in 30 minutes
TypeScript instead of JavaScript: Is it Worth Learning in 2024? A Full Breakdown
How Not to Drown in Bugs: E2E Testing of PHP Applications