When does a closure implement Fn, FnMut, and FnOnce in Rust?
I'm new to Rust and trying to understand closures. I've read about the Fn, FnMut, and FnOnce traits, but I don't fully understand when the compiler chooses which one. I wrote a small example:\n\n```rust\nfn main() {\n let x = 10;\n let print_x = || println!("{}", x); // Closure 1\n let mut y = String::from("hello");\n let append = || y.push_str(" world"); // Closure 2\n let z = String::from("rust");\n let consume = || drop(z); // Closure 3\n}\n```\n\nWhy does the first closure work as Fn, the second as FnMut, and the third as FnOnce? And how does this affect how many times I can call the closure? If I pass such a closure to a function, how do I know which trait it expects? I would appreciate an explanation with examples.
No answers yet.
Log in to leave an answer