Dynamic trait objects with GAT lifetimes using work-around on stable Rust 1.65

There is a way! But, it is also pretty convoluted.

When Rust sees something like &'a Foo<'b> in certain positions, such as a parameter type to a function, it automatically assumes some implied bounds such as 'b: 'a. The idea is that one can never construct a non-well-formed &'a Foo<'b> where this bound isn't true, so the function can just assume that it's true -- can assume that its inputs are well-formed. (If an input is not well-formed, we're already into Undefined Behavior anyway.)

So the way you can emulate some sort of for<'a where 'b: 'a> bound is to have some sort of "witness" in the context of the bound that implies 'b: 'a, like a [&'a &'b (); 0] or something. Here's a walkthrough of the idea.


Using such a witness gets rid of one error in your latest playground, but we're still stuck with the vague higher-ranked error.

I think what is actually needed is someway to introduce such a witness into your trait implementation bounds, and not just a particular method. Unfortunately I'm not sure how to do that off the top of my head (but I'm still poking).

(For example, even though the error went away on that method implementation, the trait bounds on the implementation itself don't impose any cap on for<'foo>. Probably the implementation just won't be applicable where it counts.)

Putting lifetimes bounds on the generic::{Foo, Bar} traits itself gets rid of the method error as well (though I'm not sure the bounds are actually desired). Here I've also added a boxed method that shifts what the vague higher-ranked lifetime error complains about.

3 Likes