Avatar ·

Idiomatic callbacks in Rust: how to properly pass functions and closures

Hello, colleagues! I started learning Rust after C++ and can't understand how to properly do callbacks. In C++ I just passed std::function or a function pointer. Here everything is stricter with ownership and lifetimes. Problem: I want to write a simple event handler. There is a Button struct that should call a user function when pressed. In C++ I would do it like this: ```cpp struct Button { std::function onClick; void press() { if(onClick) onClick(); } }; ``` Trying to rewrite in Rust: ```rust struct Button { callback: fn(), // trying function pointer } impl Button { fn press(&self) { (self.callback)(); } } ``` This only works for regular functions, but not for closures that capture variables. If I write: