Using references with stored functions


I have issues understanding how Rust tracks the use of references. Internally, there must be more to it than just lifetimes because despite proper lifetime annotations Rust claims that a reference is being used despite the fact that it isn’t.

See my MWE on the playground: What could be the problem here? What part of closures/lifetimes/borrowing do I not understand fully?

I hope that someone of the community can point me towards the correct solution.

Thanks a lot,

In your example, x is derived from i because the function has signature fn(&i32) -> &String which is short for for<'a> fn(&'a i32) -> &'a String. But your explicit annotation says it should be derived from self, which is a conflict and produces the error.


Here’s a version that compiles:

However, implementing storedfn is going to be tricky: conceptually, you’re going to need to allocate a String and then return a reference to it within a free function. However, the string will be immediately dropped after leaving storedfn, so the reference will not live long enough. It’s simply not possible unless storedfn returns a reference to a string that is stored in some other data structure.

1 Like

Wow, thanks, this is awesome. Now that I see your solution it seems so obvious! All you have to do is to remove the lifetime annotation from fn runme and put it upfront onto the trait.

About implementing the storedfn: You are right, that will be tricky; perhaps I can change the String reference for a String value. I have to look into this. (Actually, in my code this is a custom data structure anyway.)

1 Like