Conversation

There's an curious problem with #Rustlang lifetimes I just ran into: in real code, there is function that operates on state that contains borrowed stuff, which is fine by itself. However, in test code, I'd like to separate preparing that state from the testing code.
2
3
Here's the problem:, I'm unable to extract the preparing code to a function because it can't return the state without allocating also the referenced state, and bundling them in the same return value is a self-referencing, immovable type.
1
1
One way to solve this is to create the state-preparing function as a "context manager", that then calls the testing code. However, this feels a very awkward pattern. Then, there are a few more general ways to solve this that retain the composable nature of functions a bit better.
1
1
One is to hand an untyped arena to the state-preparing function. It can then allocate. Untypedness ensures that the caller doesn't have to care *what* the function allocates as that is essentially an implementation detail. I'm not sure whether there are good crates for this.
2
1
One, even better way, is if the compiler supported self-referential structs with "existential lifetimes". However, this isn't the case. However, this pattern would be the cleanest, as it would allow abstracting away all the implementation details from the viewpoint of the caller.
2
2
We've actually run up against the need for existential lifetimes a bunch at work sometimes in this exact use case (extracting test functions) - it definitely feels like a missing part of the type system.
1
1