Sharing what I learned about Rust functions and closures

74 points lllkong 12 comments

Hello Rustaceans!

When I first started working with Rust, I struggled with functions and closures for quite a while. I'd hit compiler errors about closures not being accepted as function parameters, or closures that could only be called once.

The whole Fn/FnMut/FnOnce thing felt like magic, and not the good kind.

Eventually, with more experience and study, it all finally made sense to me. Turns out every closure becomes a compiler-generated struct, every function has its own unique type, function names aren't function pointers, and much more.

I've been meaning to write this up for a while, so this post is my wrap-up on functions and closures after working with them for some time.

Would love to hear your feedback and thoughts. Thank you for reading!