error: lifetime may not live long enough
--> src/main.rs:39:9
|
36 | impl<'bld, 'res> MyResponseBuilder<'bld, 'res> {
| ---- ---- lifetime `'res` defined here
| |
| lifetime `'bld` defined here
...
39 | / Response {
40 | | data: self.buffer.finish(),
41 | | }
| |_________^ method was supposed to return data with lifetime `'res` but it is returning data with lifetime `'bld`
|
= help: consider adding the following bound: `'bld: 'res`
error: could not compile `playground` (bin "playground") due to 1 previous error
In this program, I tried to build a response using a temporary builder named MyResponseBuilder. The generated response itself is a reference to a byte slice owned by ResponseBufferInAnotherModule. Since the response and the builder require different lifetimes, I named them as 'res and 'bld respectively. The error message advises adding 'bld: 'res, but I want 'bld to be shorter than 'res.
Something that might work (?) is removing the intermediate MyResponseBuilder struct. Implement build_with_bool directly on ResponseSerializer: Rust Playground (rust-lang.org)
This is my best guess at something that can still fit your intended API constraints while being expressible in Rust. The problem with this is that once you call process once, you can't use the input ResponseSerializerever again. This is what the links above are describing.
Im addition to the "borrowed forever" problems (which may be fixable), this can't work as written:
because the Response<'_> borrows the local MyResponseBuilder<'_, '_>. Sometimes things like that are possible when reborrowing references directly, but they are not possible when going through struct-borrowing methods like you have.
ResponseBufferInAnotherModule is a state-aware struct and consists of methods which panic when its state is incorrect. The responsibility of MyResponseBuilder is to provide safer interface for process() by encapsulating state-related complexity. My intention of this design is to hide the complexity of ResponseBufferInAnotherModule from process() by introducing MyResponseBuilder.
This way, Response contains correctly set ResponseBufferInAnotherModule value. Caller of process() can get the generated byte slice by calling finish() method or reuse ResponseBufferInAnotherModule for next tasks.