Rust callback patterns

I was hoping someone could point me in the right direction about how to interface with a library that implements callback patterns. I am using the rust bindings for the paho-mqtt library. I tried a few of the different clients and wanted to use the async client.

In the past when I used paho with python I could subclass from the mqtt client and add my own methods to the client. It is pretty easy to point the new client to your own new method to handle incoming messages. Since I have be trying rust I it seems I should use composition instead of inheritance. So I created a struct that encapsulates the mqtt async client and some of my own variables.

Once I have this I have create methods for this client. I wanted to add one that handles a message. It seems the async client will do this as a callback. The problem is the callback takes the libs client as a param not my struct that wraps it. I can't seem to figure out a way to pass my client to the callback or make the callback point to a method off of my client struct. Every post I have seen on this seems needlessly complex for what I think is something simple.

Looking through the examples in the lib reminds me of 75% of libs. They give an example of using it from main. Everything seems neat and clean because there is no encapsulation. More real world examples would be nice.

Example: from github

Looking through the examples in the lib reminds me of 75% of libs. They give an example of using it from main. Everything seems neat and clean because there is no encapsulation. More real world examples would be nice.

I can't help you with the callback solution but one nice thing about crates.io is that you can find other crates that use the crate.

https://crates.io/crates/paho-mqtt/reverse_dependencies

These crates might contain real world examples.

1 Like

Thanks. Interesting site I will use in the future.

My initial stab is to move the variables needed in the callback into a closure for the callback. It works, but then the variables are no longer accessible in the client struct. It also litters the code with closures. I am sure Javascript developers will love that but as a code organization freak I think it makes the code less readable.