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:
No answers yet.
Log in to leave an answer
Blogs
Error Handling in Java: From try/catch to Advanced Techniques
Rule of Three in C++: What Every Developer Should Know
Deploying a Kotlin Application on VPS: A Step-by-Step Guide from A to Z
Copying to Clipboard in JavaScript: 3 Working Methods