How to create a closure whose return type is an opaque type with hrtb?

The problem is how to make this compile:

|x: &i32| {
    move || *x
error: lifetime may not live long enough
 --> src/
2 |     destination(|x: &i32| {
  |                     -   - return type of closure `{closure@src/ 3:16}` contains a lifetime `'2`
  |                     |
  |                     let's call the lifetime of this reference `'1`
3 |         move || x
  |         ^^^^^^^^^ returning this value requires that `'1` must outlive `'2`

It must be a closure, not a function pointer.

It might not be possible without type erasure. This is the same problem one runs into mixing higher-ranked trait bounds with future-returning closures. The compiler isn't good enough at figuring out when a closure should be generic over the input lifetime and pass that lifetime to the output, and the unnameable nature of futures/closures stymies one's attempts to force the inference in the typical ways (e.g. an identify function).

With type erasure (and forcing inference).

Got it. Thanks.

Note: This is doable on nightly (without type erasure).


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.