Not to mention that doesn't compile either... To actually get it to compile, I need to define the closure type in the calling function's (or impl's) type definitions.
Anyway. This is pretty hideous, and I was wondering if anyone else has come up with an elegant solution for this kind of situation.
I should also mention, that I understand the compiler needs to know the type of the parameter to generate code for the side of the branch when the Option isn't None, but I'd be happy with a solution that compile-time specialized the function into a version that totally omitted the non-None branches. But I couldn't figure out the right way to do that without some really ugly macros.
So I've been playing with this a bit more, and I was getting more comfortable with the not-so-ugly solution @quinedot proposed of having a const declared that casual users could just pass in without thinking about it.
And all seemed well in the world until I tried to move the declaration of the const into a library. Now, presumably because of dynamic linking, I'm getting cannot infer type errors.
Equally troubling, this also hints that the compiler won't be able to optimize away the const if it's part of a separate binary object.
Instead of making the closure optional, you could also provide a nop or identity function to use as the argument when users don’t need any special behavior— Then your wrapper function becomes a trivial 1-line convenience function.
Thanks for the reply. I tried that, but the trouble is that the closure's return type is a generic. So the no-op function needs to be specialized by the compiler, even though it ultimately doesn't matter.
So in practice I ended up in exactly the same boat of "cannot infer type" errors.
It works great when it's all in one file. But as soon as the no-op closure is imported from a library (the same library that contains the function I'm passing the closure to), the calling code won't compile because it complains the type isn't known.
To repeat my pattern presented in this answer, a zero-sized option using an uninhabited function type appears to be an elegant solution to me. This will guaranteed not generate any non-None branches anymore.