When does a closure implement the Fn, FnMut, and FnOnce traits in Rust?
Hello, colleagues! I started learning Rust and can't figure out closures. The documentation says that every closure automatically implements one or more traits: `Fn`, `FnMut`, and `FnOnce`. But I don't understand what this depends on.
Let's say I have simple code:
```rust
let mut x = 5;
let add_to_x = |y| x += y; // closure that mutates x
let print_x = || println!("{}", x); // closure that reads x
```
Why can `add_to_x` not be used as `Fn`, but `print_x` can? And when does a closure become `FnOnce`? I tried passing closures to functions with different trait bounds, and the compiler complains that the trait is not implemented.
Can you explain in simple terms how the Rust compiler decides which trait to implement for a closure? And how does this affect
No answers yet.
Log in to leave an answer
Blogs
Working with Dates and Time in Swift: Advanced Techniques
Server-Sent Events in C++: Real-time Without Magic and Extra Libraries
Property-based Testing in Rust: How to Catch Bugs You Weren't Looking For