Note that this works fine if you drop the
fn(&Data) bit and let type inference do its thing.
The technical reason for why you’re getting this error (or my understanding of it anyway) is that
'a in the
Data impl is meant to be linked to the concrete lifetime of some actual object, but when you reference it using the type (
Data::printer), it doesn’t know what object to bind the lifetime to.
When I’m designing an API I generally try to either be generic over any type of callable so people can use closures, you can’t store an array of closures though because each closure is its own type and arrays can only contain homogeneous types.
It sounds like you may have an X-Y problem. I’ve done a lot of parser work and even written several toy languages and parser/serialization libraries for custom file formats at work and never found a situation where I’m using an array of function pointers. That doesn’t actually mean much though because we’re probably doing things in completely different ways
If you can explain a bit more about how you’re trying to approach things maybe I (or someone else) may see an easy way to express what you’re trying to do.
A small nit: you’re probably also wanting to use a
&'a str as the type of
x instead. A
String is a string of characters explicitly allocated on the heap, whereas a
&str is a slice into any string (whether it’s on the heap, compiled into the executable, or sitting on the stack somewhere). It’s a similar idea to the difference between a
std::vector if you’re familiar with C++) and an array. It’s a bit of a learning curve, but knowing the difference between a heap allocated string and a string slice can often make a decent performance difference when you’re writing parsers because of all the small strings you’re pushing around.
EDIT: I just tried using
mem::transmute to force the compiler to interpret
Data::printer as a function pointer directly and it looks like
Data::printer is actually zero-sized. So that means turning it into a function pointer probably doesn’t make sense because there’s nothing to actually point to ¯_(ツ)_/¯