Avatar ·

How to pass a function as a parameter in Rust?

Hi everyone! I just started learning Rust, and I have a problem that seems simple but I can't find the right solution. I want to write a function that takes another function as an argument to make the code more flexible.\n\nHere's what I'm trying to do:\n\n```rust\nfn apply_twice(f: ???, x: i32) -> i32 {\n f(f(x))\n}\n\nfn add_one(x: i32) -> i32 {\n x + 1\n}\n\nfn main() {\n let result = apply_twice(add_one, 5);\n println!("{}", result); // Expected 7\n}\n```\n\nI don't understand what type to specify for the `f` parameter. I tried `fn(i32) -> i32`, but the compiler complains. I've also heard about closures and the `Fn`, `FnMut`, `FnOnce` traits — but what's the difference? When to use each of them? How to pass a closure that captures variables from the outer scope?