Lifetime inference problems when creating a trait object / returning opaque type

I think basically the lifetimes on the dyn Expression become entangled with that on the writer -- you have something like

[Box<dyn Expression<'param, TestWriter<DisplayParam<'param>>> + '_>; 3]

And then you call some method with both of

&mut TestWriter<DisplayParam<'param>>
&'param [Box<... 'param ...>]

(You made things more general, but in a way that allows borrowing the expression for longer than 'param, and thus can be coerced down to borrow for exactly 'param.)

And this is the speculative part (as I've never seen the rules written down), but I think the analysis behaves as both the writer can observe the expression for 'param (as it does in your implementation), but also that the expression can observe the writer for 'param as well (perhaps the erased type has interior mutability).

Then you get an unworkable situation where dropping the boxes can perhaps observe the writer, but the writer can't last longer than the things it's borrowing from.

Smaller example.

I think this backs up the interpretation -- the param-stealing Sneaky follows your declared API, but a lifetime "flows" from the writer to the expression.

3 Likes