How to pass a closure wrapped in Rc to a third party function

Hi guys. I'm running into some trouble trying to pass a closure wrapped in an Rc to a third party function.

The function expects the closure to be FnMut(&Event) + 'static. If I pass the closure directly in, there's no problem. However, my use case is that I have a data structure that holds the closure until a certain point, at which I call the function and pass the closure. Since my data structure owns the closure, but the function I'm passing it to also wants to own the closure, I thought that this would be an ideal use case for Rc. However, when I try to pass the Rc wrapped closure I get this error:

expected a `FnMut<(&web_sys::Event,)>` closure, found `std::rc::Rc<Box<dyn for<'r> Fn(&'r web_sys::Event)>>`
the trait `for<'r> FnMut<(&'r web_sys::Event,)>` is not implemented for `std::rc::Rc<Box<dyn for<'r> Fn(&'r web_sys::Event)>>`

I'm not entirely sure what this error is trying to tell me. Can anyone explain what it means and, more importantly, does anyone know if it simply isn't possible to pass an Rc to a function that isn't expecting one?

The current Fn impls only pass through &F and Box<F> implicitly, so Rc is not directly callable. You could pass a new closure around it though, like move |event| (*my_rc)(event).

Also, Rc<Box<_>> has two layers of allocation -- is there a reason you aren't using Rc<dyn Fn>?

1 Like

Thanks @cuviper! That did the trick. Also, to answer your question, there was no reason to have Rc<Box>>. It was just a pattern that I saw often so I copied it without clearly understanding why I was using it. Thanks helping me out. I removed the box and wrapped the Rc in another closure and I had no problem.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.