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.
Conversation
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
This basically brings to scope a lifetime parameter the function is able to use when it creates the state with borrows.
1
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
Replying to
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.
Replying to
Year ago I wrote a super long blog post about the shortcomings of the borrowing and mutability system, and this was one of the points: link.medium.com/ikhb2wzQoY Maybe it's time to write another that focuses on the problem and examines the solution space bit more...!
1
1
Ohh, I remember that one! We were bigs fan of it!
1
1
Show replies

