How to drop selected borrows when converting a struct via trait to another, all called from a wrapper function?

I'm sorry if the title is unclear - I couldn't figure a better one.

Also my apologies for my English or if my terminology isn't exact, I'm not a native speaker (open to any feedback.)

TL;DR: Here's reproducible example in the playground..

The problem

  • A context value has the make_scope method which receives an input value.
  • The input value implements the Begin trait which begin method consumes it and returns end value which implements the End trait.
  • When the new end value is created, some of the borrows of the input value are supposed to be dropped while others are moved to the end value. This is what I'm trying to achieve.
  • The make_scope returns a value which implements Scope trait and stores context by reference and end by value (that's why the trait is needed - it depends on type of the input value which determines type of the end value.)
  • While the returned scope value exists, borrows dropped after begin was called need to be accessed. This is what doesn't work for me.

What I tried

  • First, I specified 'begin and 'end lifetimes as generic parameters of the Begin trait. Implementation then uses them to differentiate which references need to be dropped and which need to be transferred to the end.
  • The compiler suggested to add the + use<'this, 'end, T> to the output type of make_scope method. However, when implemented, compiler then complains that the output also captures 'begin lifetime (which is undesired.)
  • When I expand (inline) make_scope, everything starts working just fine. However, that's undesired as there's some more work in the function (unrelated to the issue, i.e. not in the example.)
  • Various other experiments which lead nowhere. E.g. try to specify output of begin as both type alias and impl declaration with and without + use<'end>.

What I'm trying to solve (the underlying goal)

I have a couple of begin/end functions. Begin functions tend to receive lots of input parameters and lots of them could use default values. But Rust doesn't support named arguments nor default parameters which makes using such functions difficult, therefore I encapsulate them with a struct which implements the Default trait.

Additionally, these functions need some common values/references which are stored in the Context struct (and which is also needed between begin/end calls.)

And finally, the begin function requires that end must be called later. (I use Drop trait for that - not included in the example for more explicit flow.)

Some of the parameters passed to begin are references to containers which are owned by a struct which needs to be used between begin and end and I don't want to copy them. That means they need to be borrowed for the duration of the begin call, but NOT between begin and end. I mean - they could be, they're not needed in that block, but that prevents calling mutable methods on the value which is really desired.

Playground Example

Here's the playground example..

  • Does not compile, so you can see the error immediately.
  • When the let mut scope = context.make_scope(foo); line near the end of the file is commented and following block uncommented (which contains exactly same code as the method), everything works as desired.
use std::marker::PhantomData;

// 'begin ... lifetime of references which need to live only until begin() call.
// 'end ... lifetime of references which need to live until the end.
trait Begin<'begin, 'end> {
    // Result of begin -> no longer capture 'begin, just 'end.
    type Out: End<'end>;

    // Begin uses 'begin references and then drops them. No longer accessing.
    // Returns new structure which can access only 'end references.
    fn begin(self) -> Self::Out;
}

trait End<'end> {
    fn end(&mut self);
}

struct Foo<'begin, 'end> {
    ref_begin: &'begin i32,
    ref_end: &'end i32,
}

struct FooEnd<'end> {
    ref_end: &'end i32,
}

impl<'begin, 'end> Begin<'begin, 'end> for Foo<'begin, 'end> {
    type Out = FooEnd<'end>;

    fn begin(self) -> Self::Out {
        // This is the last time ref_begin is supposed to be accessible.
        println!("Foo begin ({}, {})", self.ref_begin, self.ref_end);

        // From now on, ref_begin is supposed to be unborrowed while keeping reference to end.
        return FooEnd {
            ref_end: self.ref_end,
        };
    }
}

impl<'end> End<'end> for FooEnd<'end> {
    // (Cannot consume self, because in some cases, this is called from drop...)
    fn end(&mut self) {
        println!("Foo end ({})", self.ref_end);
    }
}

// There might me multiple kinds of scope, the Begin and End is only one of them.
trait Scope {
    fn finish(&mut self);
}

// Scope implementation for the End types.
struct ScopeForEnd<'end, 'context, T: End<'end>> {
    end: T,
    context: &'context mut Context,
    _marker: PhantomData<&'end ()>,
}

impl<'end, 'context, T: End<'end>> Scope for ScopeForEnd<'end, 'context, T> {
    fn finish(&mut self) {
        let _ = self.context;
        self.end.end();
    }
}

struct Context {}

impl Context {
    // The idea is:
    // - Call begin() on the x and then drop 'begin references.
    // - Create Scope implementation which:
    //   - Refernces self
    //   - References 'end values.
    //   - !!! DOES NOT REFERENCE 'begin VALUES !!!
    pub fn make_scope<'this, 'begin, 'end, T>(&'this mut self, x: T) -> impl Scope
    // The compiler suggest to write use<..> below, but when uncommented:
    // error[E0700]: hidden type for `impl foo::Scope` captures lifetime that does not appear in bounds
    // [...]
    //     |                                    ------ hidden type `ScopeForEnd<'end, 'this, <T as Begin<'begin, 'end>>::Out>` captures the lifetime `'begin` as defined here
    // + use<'this, 'end, T>
    where
        T: Begin<'begin, 'end>,
    {
        return ScopeForEnd {
            end: x.begin(),
            context: self,
            _marker: PhantomData,
        };
    }
}

fn main() {
    let mut value_begin: i32 = 13;
    let value_end: i32 = 17;

    let mut context = Context {};

    let foo = Foo {
        ref_begin: &value_begin,
        ref_end: &value_end,
    };

    // Here, create Scope implementation.
    let mut scope = context.make_scope(foo);

    /*
    // When this is uncommented and replaces the scope above,
    // everything compiles just fine.
    let mut scope = ScopeForEnd {
        end: foo.begin(),
        context: &mut context,
        _marker: PhantomData,
    };
    */
    
    // Here, after Scope impl is created, the value_begin should be no longer borrowed.
    // Scope must exist.

    // Here's the error:
    // error[E0506]: cannot assign to `value_begin` because it is borrowed
    value_begin += 1;
    println!("Between begin and end ({})", value_begin);

    // After this point, scope is no longer needed.
    scope.finish();
    
    let _ = value_end;
    let _ = context;
}

T has a 'begin lifetime inside, so if you capture that type you also capture the lifetime.

Thank you for your time!

I'm sorry, I should have mentioned that in the original post: when I remove the T, it triggers the following compiler error:

error: `impl Trait` must mention all type parameters in scope in `use<...>`
[...]
    |
543 |           pub fn make_scope<'this, 'begin, 'end, T>(
    |                                                  - type parameter is implicitly captured by this `impl Trait`

and suggestion to add it to the use<...>.

I'm not sure I understand what problem you are trying to solve, but guessing from the code, you need partial/split borrow for it to work.

unfortunately, partial borrow is not directly expressisble using generic bounds. when it is a concrete type, the borrow checker is smart enough to infer it, but when it goes under a generic context, it's no longer able to do the check.

the usual workaround is to modify the trait so the splitting is explicit. for instance, instead of fn begin(self) -> Self::Out, you change it to something like fn begin(self) ->(Self::Out, Self::Residual);, where Self::Out and Self::Residual carries different lifetimes.

however, whatever problem you are trying to solve, this is a very convoluted solution. I feel like there's simpler solutions being missed. but this is just my speculation. I don't understand the problem to suggest anything.

Please check if this works for your purposes.

I'm not sure I understand what problem you are trying to solve, [...]

Oh, I'm sorry for being unclear.

but guessing from the code, you need partial/split borrow for it to work. [...]

If I understand you correctly, you're saying that whatever needs to be accessed between begin and end and is used to build the structure which implements Begin, should be returned by begin (the residual) and then used in that block (instead of being accessed directly.) Regrettably, that doesn't solve the issue because what's needed between begin and end is the ability to call mutable methods on value which is source of the input data (needed only during begin call, not later.) And splitting that is undesired for clean interface purposes.

But that's totally my fault - I didn't make this obvious in the code example, only in the text description, so your suggestion definitely works for the example. I made that too simple when trying to build a minimal reproducible example, my bad.

however, whatever problem you are trying to solve, this is a very convoluted solution. I feel like there's simpler solutions being missed. but this is just my speculation.

I feel so, too - I mean, my example already feels more complicated than it should. That's definitely skill issue on my part.

I don't understand the problem to suggest anything.

Again, my apologizes for not being able to explain it more clearly.

Anyway, thank you for your answer!

Thank you, again!

The example works, but regrettably, I don't understand the principle behind it so I'm not able to transfer that workaround back to my project - but that's out of the scope of this question and skill issue on my part, so I'm gong to mark this as solution.

I mean, the main part was to move impl Scope + use<'this, 'end, T> somewhere that doesn't capture the whole T, and I found that moving it into Begin trait definition (as an associated type; and as 'this lifetime isn't present there, it's a generic associated type) made things fit together.

Yes, however many impl Scope-shaped returns you have, you'll have to replace each with a new associated type, which is a drawback.

I mean, the main part was to move impl Scope + use<'this, 'end, T> somewhere that doesn't capture the whole T, and I found that moving it into Begin trait definition (as an associated type; and as 'this lifetime isn't present there, it's a generic associated type) made things fit together.

I'm sorry, but I don't understand your explanation. First, the issue was captured 'begin, not 'this. Second, in the original code, Begin trait already had the associated type Out on same level as your Fi - I don't understand how one captures 'begin and the other does not ('this isn't defined in that scope in any case.)

Yes, however many impl Scope-shaped returns you have, you'll have to replace each with a new associated type, which is a drawback.

That's not a problem, this is very work-in-progress.


Anyway, after taking a rest, I tried to integrate your solution again and even though I still don't understand it, I managed to make it work. After that, I started simplifying the code (removing lifetimes to see what the compiler accepts) and in the end, all that's needed is to specify the output type to T::Fi<'this> without that nested trait condition (which is the part which confused me the most.)

After that, I experimented a bit more and finally found the root of the issue:

  • When the return type is impl Scope, it captures everything and use<...> doesn't allow to reduce captured lifetimes in my case.
  • When the return type is explicitly ScopeForEnd<...>, it captures only what's actually captured.
  • When the return type is associated type, i.e. T::Fi<...> which is specified to be ScopeForEnd<...>, it also works.

And with that, most of the lifetimes can be cleared (e.g. 'end is just an implementation detail which doesn't need to be exposed in all traits.)

The disadvantage is that ScopeForEnd must be made public, even though it's just an implementation detail (which is why I originally wrote the return as impl Scope.)

The cleaned example is (showing both variants):

trait Begin {
    // Results of begin_a and begin_b -> these no longer are supposed to capture selected references of Self.
    type OutA: End;
    type OutB<'context>: Scope;

    // Begin uses some inner references and then drops them. No longer accessing.
    // Returns new structure which can access only selected references from original Self.
    fn begin_a<'context>(self, context: &'context mut Context) -> Self::OutA;
    fn begin_b<'context>(self, context: &'context mut Context) -> Self::OutB<'context>;
}

trait End {
    fn end(&mut self);
}

struct Foo<'begin, 'end> {
    ref_begin: &'begin i32,
    ref_end: &'end i32,
}

struct FooEnd<'end> {
    ref_end: &'end i32,
}

impl<'begin, 'end> Begin for Foo<'begin, 'end> {
    type OutA = FooEnd<'end>;
    type OutB<'context> = ScopeForEnd<'context, FooEnd<'end>>;

    fn begin_a<'context>(self, context: &'context mut Context) -> Self::OutA {
        // This is the last time ref_begin is supposed to be borrowed.
        println!("Foo begin ({}, {})", self.ref_begin, self.ref_end);

        // From now on, ref_begin is supposed to be unborrowed while keeping reference to ref_end.
        return FooEnd {
            ref_end: self.ref_end,
        };
    }

    fn begin_b<'context>(self, context: &'context mut Context) -> Self::OutB<'context> {
        // This is the last time ref_begin is supposed to be borrowed.
        println!("Foo begin ({}, {})", self.ref_begin, self.ref_end);

        // From now on, ref_begin is supposed to be unborrowed while keeping reference to ref_end.
        return ScopeForEnd {
            end: FooEnd {
                ref_end: self.ref_end,
            },
            context,
        };
    }
}

impl<'end> End for FooEnd<'end> {
    // (Cannot consume self, because in some cases, this is called from drop...)
    fn end(&mut self) {
        println!("Foo end ({})", self.ref_end);
    }
}

// There might me multiple kinds of scope, the Begin and End is only one of them.
trait Scope {
    fn finish(&mut self);
}

// Scope implementation for the End types.
struct ScopeForEnd<'context, T: End> {
    end: T,
    context: &'context mut Context,
}

impl<'context, T: End> Scope for ScopeForEnd<'context, T> {
    fn finish(&mut self) {
        self.end.end();
    }
}

struct Context {}

impl Context {
    // The idea is:
    // - Call begin() on the x and then drop "begin" references.
    // - Create Scope implementation which:
    //   - References self (the context)
    //   - References "end" values.
    //   - !!! DOES NOT REFERENCE "begin" VALUES !!!
    pub fn make_scope_a<'this, T>(&'this mut self, x: T) -> ScopeForEnd<'this, T::OutA>
    where
        T: Begin,
    {
        return ScopeForEnd {
            end: x.begin_a(self),
            context: self,
        };
    }

    pub fn make_scope_b<'this, T>(&'this mut self, x: T) -> T::OutB<'this>
    where
        T: Begin,
    {
        return x.begin_b(self);
    }
}

fn main() {
    let mut value_begin: i32 = 13;
    let mut value_end: i32 = 17;

    let mut context = Context {};

    let foo = Foo {
        ref_begin: &value_begin,
        ref_end: &value_end,
    };

    // Here, create Scope implementation.
    let mut scope = context.make_scope_a(foo);

    // Alternative solution: uncomment this and comment scope above.
    //let mut scope = context.make_scope_b(foo);

    // Here, after Scope impl is created, the value_begin should be no longer borrowed.
    // Scope must exist.

    // Here's where the error originally occurred:
    // error[E0506]: cannot assign to `value_begin` because it is borrowed
    value_begin += 1;
    println!("Between begin and end ({})", value_begin);

    // After this point, scope is no longer needed.
    scope.finish();
}

I still don't understand the underlying mechanics of the issue, but I at least understand both solutions.

Edit: wrong formatting.

The core problem is that any concrete type that implements Begin<'begin, 'end> captures the lifetime 'begin. When you have a plain impl Scope, or an impl Scope + use<…, T>, the compiler substitutes that concrete type in place of the T. In your case, you have pub fn make_scope<'this, 'begin, 'end, T>(&'this mut self, x: T) -> impl Scope, which from the compiler's point of view is the same as:

pub fn make_scope<'this, 'begin, 'end, T>(&'this mut self, x: T) -> impl Scope + use<'this, 'end, T>`

And that's where it all starts to go horribly wrong for you - you see like impl Scope, which does not contain a visible 'begin, and wonder where the compiler is getting 'begin from - but the compiler sees something closer (not real Rust syntax, just illustrative) to impl Scope + use<'end, impl Begin<'begin, 'end>>, and is complaining because the 'begin in the impl Begin is captured and doesn't end where you expect it to as a result (since all the compiler knows about T at this point is that it's impl Begin<'begin, 'end>.

In contrast, your inlined implementation is transparent to the compiler - it's looking at the equivalent of pub fn make_scope<'this, 'begin, 'end, T>(&'this mut self, x: Foo<'begin, 'end>) -> impl Scope + use<'this, 'end>, and this doesn't capture 'begin at all in the return type.

The only way round this is to not capture T, but to capture either the associated type <T as Begin>::Out or the relevant concrete type. Either of those avoids the problem that Rust can't see the type, and makes it happy again.

Ah, I see, thank you very much for your explanation, I (hopefully) understand it now. I somehow missed this behavior when I learned about using impl for return type, sorry for the trouble.

An alternative fix for the OP is

    // Using `+ 'this` instead of `'not_begin` would probably be good enough
    pub fn make_scope<'this, 'begin, 'end, 'not_begin, T>(
        &'this mut self,
        x: T
    ) -> impl Scope + 'not_begin
    where
        T: Begin<'begin, 'end, Out: 'not_begin>,
        'this: 'not_begin,
        'end: 'not_begin,
    { ... }

Then the return type will still capture the lifetime in some sense, but uses of the the returned value won't keep the 'begin borrow alive.

Or in the latest code,

    pub fn make_scope<'this, T>(&'this mut self, x: T) -> impl Scope + 'this
    where
        T: Begin<OutA: 'this>,
    {

An alternative fix for the OP [...]

That's not an alternative, that's THE solution. Thank you!

I was able to apply it at my (a bit more elaborate) code; it's now as simple as I hoped, so thanks again!

I'm just not sure how to generalize the solution to learn from this problem, but I'll try to keep it in mind for the future.

Edit: fix formatting.

Let me present a related scenario that doesn't involve -> impl Trait. Hopefully this walkthrough is intuitive.

Let's say you had some

trait Opaque<'this, T: Begin> {
    type Ty: Scope;
    fn construct(ctx: &'this mut Context, t: T) -> Self::Ty;
}

And in a generic context, where you have to support every possible implementation that supports what you want to pass in, you try to

// The bound means "I can pass in any `Foo<'begin, 'end>`"
// (and any `&'this mut Context`).
fn ex<O: for<'this, 'begin, 'end> Opaque<'this, Foo<'begin, 'end>>>() {
    let mut value_begin: i32 = 13;
    let mut value_end: i32 = 17;
    let mut context = Context {};
    let foo = Foo {
        ref_begin: &value_begin,
        ref_end: &value_end,
    };

    let mut scope = O::construct(&mut context, foo);
    value_begin += 1;
    println!("Between begin and end ({})", value_begin);
    scope.finish();
}

You'll get the error,[1] because there's a possible implementation

struct HoldOnToEverything<'this, T> {
    ctx: &'this mut Context,
    begin: T,
}

// Note: `T` can be `Foo<'begin, 'end>` for any `'begin`, `'end` here.
// That is, `Whatever` satisfies the `O: ...` bound on `fn ex`.
impl<'this, T: Begin> Opaque<'this, T> for Whatever {
   type Ty = HoldOnToEverything<'this, T>;
    fn construct(ctx: &'this mut Context, begin: T) -> Self::Ty {
        HoldOnToEverything { ctx, begin }
    }
}

In other words, the compiler is correct to throw an error here.

But if you change the Opaque trait...

trait Opaque<'this, T: Begin> {
    type Ty: Scope + 'this; // <--- `+ 'this` is new
    fn construct(ctx: &'this mut Context, t: T) -> Self::Ty;
}

...then it compiles, because there is no possible implementation where the T parameter to Opaque can both be Foo<'begin, 'end> for any 'begin and 'end, and also be part of the definition of Ty.

E.g. here's what happens to the implementation for Whatever:

error[E0309]: the parameter type `T` may not live long enough
   --> src/main.rs:117:14
    |
116 | impl<'this, T: Begin> Opaque<'this, T> for Whatever {
    |      ----- the parameter type `T` must be valid for the lifetime `'this` as defined here...
117 |    type Ty = HoldOnToEverything<'this, T>;
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `HoldOnToEverything<'this, T>` will meet its required lifetime bounds...
    |
note: ...that is required by this bound
   --> src/main.rs:124:22
    |
124 |     type Ty: Scope + 'this;
    |                      ^^^^^
help: consider adding an explicit lifetime bound
    |
116 | impl<'this, T: Begin + 'this> Opaque<'this, T> for Whatever {

If you add the suggested bound, the implementation compiles again, but then Whatever no longer satisfies this bound:

//    vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
fn ex<O: for<'this, 'begin, 'end> Opaque<'this, Foo<'begin, 'end>>>() {
   --> src/main.rs:144:5
    |
144 |     ex::<Whatever>();
    |     ^^^^^^^^^^^^^^^^ implementation of `Begin` is not general enough
    |
    = note: `Begin` would have to be implemented for the type `Foo<'0, 'end>`, for any lifetime `'0`...
    = note: ...but `Begin` is actually implemented for the type `Foo<'1, '_>`, for some specific lifetime `'1`

Alright, now back to -> impl Scope. To an outside consumer, this method:

impl Context {
    pub fn make_scope_a<'this, T>(&'this mut self, x: T) -> impl Scope
    where
        T: Begin,

Is analogous to being in a situation like this:

trait Opaque<'this, T: Begin> {
    type Ty: Scope; // No bound (yet)
    fn construct(ctx: &'this mut Context, t: T) -> Self::Ty;
}

// We don't have a way to write `O: for<T: Begin> ...` bounds so far...
// > "for all `T` where `T: Begin`, `O` satisifies ..."
// ...but pretend for now we did.
//
// The point is that the `-> impl Scope` is defined for all possible inputs
// to `Context::make_scope_a`.
fn ex<O: for<'this, T: Begin> Opaque<'this, T>>() {
    // Calling `Context::make_scope_a` is like calling `O::construct`
}

You know you can pass in any Foo<'begin, 'end> (or any other T: Begin). And you know you'll get back something that implements Scope.[2] But for all you know, it holds on to the whole Foo<'begin, 'end>, like Whatever's implementation.

This change

 impl Context {
-    pub fn make_scope_a<'this, T>(&'this mut self, x: T) -> impl Scope
+    pub fn make_scope_a<'this, T>(&'this mut self, x: T) -> impl Scope + 'this
     where
         T: Begin,

Is analogous to this change

 trait Opaque<'this, T: Begin> {
-    type Ty: Scope; // No bound (yet)
+    type Ty: Scope + 'this; // <--- `+ 'this` is new
     fn construct(ctx: &'this mut Context, t: T) -> Self::Ty;
 }

and satisfies the borrow checker in main, for the same reason. There's no possible implementation that is both defined for all inputs to make_scope_a, and which materially captures T.

But then the body of make_scope_a complains until you also

 impl Context {
     pub fn make_scope_a<'this, T>(&'this mut self, x: T) -> impl Scope + 'this
     where
-         T: Begin,
+         T: Begin<OutA: 'this>,

...because you are materially capturing OutA.

The practical effect of this last change for main is that uses of the return value keep value_end borrowed in addition to context (because OutA: 'this requires 'end: 'this), which reflects the material captures and is what you wanted.[3]


Generalizing from that specific example, my mental model for -> impl Trait is

fn ex<'a, 'b, 'c, T, U: Bound>() -> impl Trait + 'a + use<'b, T, U>

// All the generics which are in the `use<..>` (explicitly or implicitly)
// or are in the other parts of `impl`
//           vvvvvvvvvvvvvvvvvvv
trait Opaque<'a, 'b, T, U: Bound> {
    type Ty: Trait + 'a; // <-- the hidden type with it's bounds
}

Where Ty can never be normalized to a concrete type (as if you had a generic O: for<*> Opaque<*>), but does leak auto traits.

You still have to learn the ins and outs of how borrow checking works with associated types, but at least that's one thing instead of two. I find it more intuitive, anyway.

Playground so you don't have to paste as much if you want to play around.


  1. error[E0506]: cannot assign to value_begin because it is borrowed ↩︎

  2. You also know the impl Scope's auto-traits, unlike the O::Ty scenario. It's not relevant to the borrow checking here so I'll say no more about that part. ↩︎

  3. Disclaimer, the example up top didn't cover this part. I can probably revisit it if you want me to. ↩︎

Thank you very much for your time and explanation!

If I understand it correctly (and to describe it in my very amateurish way), the meaning of the 'this lifetime is to tie together multiple separate borrows:

  • In the Opaque trait, tie type Ty: Scope + 'this for the output of the construct. This says 'this represents whatever is borrowed by the output.
  • In the Opaque trait, tie ctx: &'this mut Context, i.e. the output of the construct can now reference anything from the context. (That's unrelated to the problem, but it's one of my input requirements.)
  • In the Context struct, make_scope_a function, tie -> impl Scope + 'this which basically "forwards" the bound lifetime "outside" (to the caller.)
  • In the Context struct, make_scope_a function, tie T: Begin<OutA: 'this> which basically "forwards" the bound lifetime "inside" (to the type T which implements Begin/Opaque.)

And all this excludes 'begin lifetime from the output (which is my original question) not because it's explicitly excluded (which is what I attempted to achieve in my first example), but because it's not explicitly included in the 'this lifetime in the Opaque (or Begin) trait which limits the output type (with the fix.)

Or, in other words, with type Ty: Scope, Ty can be "anything" (which includes borrowing 'begin by the output type which caused my issue), but with type Ty: Scope + 'this, Ty is bound to the 'this which is then used to restrict borrows in the make_scope_a (i.e. if 'begin is not included in 'this, it's not allowed to be borrowed - which is the goal.)


In that case, the source of my error is that I explicitly learned to not use lifetimes this way. The 'this is bound to references of both instances Context and T (Opaque/Begin). When I started learning Rust, I understood that binding one lifetime to two such unrelated references is okay, because the borrow checker will consider the shorter of the two.

However, I got burned many times by thinking this way, because in these cases, the compiler complained that the T reference must live as long as the Context reference which is not true in my case which is why I unlearned to even consider using the 'this this way. The proper solution in such cases was to declare separate lifetimes for every single reference and then bind them with where 'a: 'b.

So my lesson is that I still don't fully understand when I need to use shared single lifetime and when I need to separate them. And most importantly - consider both approaches when encountering issues like this.

I agree that explicitly excluding (concretely excluding?) is a dead end here, even though it's a solution elsewhere, and arguably preferred and more intuitive. For example when I joined this conversation you had:

fn make_scope_a<'this, T>(&'this mut self, x: T) -> ScopeForEnd<'this, T::OutA>
// Call the above with `T = Foo<'begin, 'end>` and you get
fn make_scope_a(
    &'this mut self,      // borrow of `context`
    x: Foo<'begin, 'end>, // borrow of `value_begin` and `value_end`
) -> ScopeForEnd<'this, FooEnd<'end>>

Where 'begin is excluded from the output type.[1] Or if you had

    pub fn make_scope_c<'this, 'begin, 'end>(
        &'this mut self, 
        x: Foo<'begin, 'end>
    ) -> impl Scope + use<'this, 'end>

That would have also worked. But there's no direct way to exclude T but include T::OutA with -> impl Scope on stable.

Eventually there will be though!

The TAIT feature will allow more fine-grained tuning of what is captured by allowing type X<...captures...> = impl Trait:

#![feature(type_alias_impl_trait)]

// The generics replace `+ use<..>` on `make_scope_d`.
pub type Out<'this, E: End> = impl Scope;

// We need a helper to define it, because `Out<'_, T::OutA>` still mentions
// `T` on `make_scope_d`, and we need to avoid relying on `T`.
#[define_opaque(Out)]
fn private_helper<E: End>(context: &mut Context, end: E) -> Out<'_, E> {
    ScopeForEnd { context, end }
}

impl Context {
    // When called with `T = Foo<'begin, 'end>`, the output type (alias) is
    // `Out<'this, FooEnd<'end>>` and `'begin` is excluded.
    pub fn make_scope_d<'this, T: Begin>(
        &'this mut self,
        x: T
    ) -> Out<'this, <T as Begin>::OutA>
    {
        let end = x.begin_a(self);
        private_helper(self, end)
    }
}

And there are other further-future possibilities if we can some day exclude some type parameters from -> use<..>.

    // If `T` could be excluded, `use<..>` would be powerful enough to exclude
    // `T` while still including `T::OutA` without any lifetime bounds
    pub fn make_scope_e<'this, E: End, T: Begin<OutA = E>>(
        &'this mut self,
        x: T
    ) -> impl Scope + use<'this, E>

If there was a way to solve the problem with exclusion, I'd recommend it for the OP. But because there's no stable way to explicitly/concretely/directly exclude what you want to in this case, we need to fall back to something more indirect.

Then moving on to mental models for how the workaround functions...

We're using different words, and maybe deeper different mental models, but I believe the conclusion you state here is the same as mine.

The way I think of it is that we want to limit what lifetimes (borrows) can end up in Ty here (or in the concrete type behind impl Scope):

impl<'this, T: Begin> Opaque<'this, T> for BoringBlanketImpl {
    type Ty = ?;
    // Generic path: <_ as Opaque<'this, T>>::Ty
}

And without bounds, Ty could mention anything in its generic path, which includes 'this and T (and thus indirectly, any lifetimes in T). But if we add Ty: 'this, and we have a T that does not meet a 'this bound, we know that Ty cannot include T. The impl header permits such T, so in fact we can conclude that the blanket implementation as a whole doesn't put T into Ty -- because Ty must be defined for all inputs to the implementation. (And impl Scope must similarly be defined for all inputs to make_scope_a.)

I don't think I would use your phrasing exactly... I guess when I read "but with type Ty: Scope + 'this, Ty is bound to the 'this" I feel a bit of disconnect. Because without that bound, Ty could include 'this, and therefore the (generic) consumer must assume it does, even though it wasn't explicitly connected with a lifetime bound. With the bound, Ty still could include 'this, and therefore the (generic) consumer still must assume it does. But that's not what's new! What changed is what could not be included (which is T).[2]

At this point the example being incomplete is bothering me, so I'll talk about making it more complete. But this may be a distraction, so I'll hide it by default.

Because we have a T: Begin bound on the impl, it's possible for the implementation to mention T::OutA in Ty instead of mentioning T as a whole. But because there are no constraints on T::OutA, we can use the same reasoning as before to conclude that Ty can't possibly include T::OutA either.

However that means the implementation you want, which does include T::OutA, is impossible! This corresponds to the part of my walkthrough where make_scope_a complained. And the fix is analogous:

//                  vvvvvvvvvvvvv
impl<'this, T: Begin<OutA: 'this>> Opaque<'this, T> for BoringBlanketImpl {
    type Ty = ?;
}

With no bounds on Ty, any of 'this or T or T::OutA (and thus the lifetimes in them) can be included in Ty. When we add + 'this,

  • 'this can still be included because 'this: 'this (always)
  • T::OutA can still be included because T::OutA: 'this (from the impl header)
  • But T can no longer be included (because nothing in the impl header requires T: 'this)

And that's all we need for the implementation you want.

If we continued on to wire this up to my fn ex<O: for<..> Opaque ... function, though, we would find it is really challenging to express what is allowed in the form of a trait bound on O. Fortunately I don't think that's required for this part of the conversation, so I'll just stop here.

In summary, I guess when I start adding bounds as a workaround, I'm trying to maneuver the compiler into seeing that materially capturing some lifetimes is logically impossible, because it would imply a violation of the bounds.

// Everything can be materially captured; return value must keep all input
// borrows alive.
fn make_scope<'this, T: Begin>(..) -> impl Scope

// `T` can no longer be materially captured; return value must keep `'this`
// borrows alive, but need not keep borrows in `T` alive.
//
// ...including lifetimes mentionable in `T::OutA`, which results in an error
// here when you try to include `T::OutA` in the concrete return type.
fn make_scope<'this, T: Begin>(..) -> impl Scope + 'this

// `T` as a whole still can't be materially captured, but now `T::OutA` can be.
// Return value must keep `'this` and any borrows in `T::OutA` alive, but 
// need not keep other borrows in `T` (e.g. `'begin`) alive.
fn make_scope<'this, T: Begin<OutA: 'this>>(..) -> impl Scope + 'this

I'm guessing at least some of the difference in our mindset is due to what you talk about next -- the shortcut where 'this is representing the intersection of the borrow of context and the borrow in T::OutA in the output type of make_scope_a, i.e.:


That is completely valid, and I empathize. In my first contribution to this thread, I wrote

And this is an example of being very precise about how the lifetimes relate. 'not_begin represents some lifetime (borrow duration) in the intersection of 'this and 'end, without requiring any of 'this: 'end, 'end: 'this, or 'this = 'end. And the intersection of 'this and 'end is where, for example, ScopeForEnd<'this, FooEnd<'end>> is valid.[3]

:asterisk: But 'this is "probably good enough" here because it doesn't appear in trait bounds[4] and only concretely on the input self: &'this mut Context. Which is a covariant (shrinkable, "freely smaller") position, and in practice you'll never want the borrow of context to be longer than necessary.

So you might as well just say "let 'this be (implicitly shrunk to) the intersection of 'this and 'end", which amounts to replacing 'not_begin with 'this in the above code and removing all the redundant parts.

Everything I've wrote since then...

...just took that approach from the start, even though it does somewhat conflate two things that start out independent (the borrow of a Context and T) and are only connected by the output.[5]

I'm not sure I have any concrete advice on how to build intuition for reasoning like the :asterisk: marked paragraph, though. I think I got there from the experience of cracking problems like these and writing out the explanations (which occasionally reveals holes in your own understanding too).

Because it's a peeve of mine, I guess I will point out that what the book says...

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {

[...]
In practice, it means that the lifetime of the reference returned by the longest function is the same as the smaller of the lifetimes of the values referred to by the function arguments.

...is misleading at best.[6] A much better practical description is "uses of the return value keep *x and *y borrowed".

What's entirely missing as it pertains to this conversation is an exploration of when using the same lifetime is or is not "good enough" (which admittedly requires tackling the somewhat gnarly topic of variance).


  1. Syntactically, but also because the three lifetimes are independent. If Foo<'begin, 'end> required 'begin: 'end there would still be a relationship. ↩︎

  2. In both cases, Ty isn't required to include 'this. But that's not something the generic consumer can assume; they must consider every valid possibility -- everything the blanket implementation could possibly do. ↩︎

  3. If we had a syntax for intersections ('a & 'b) in addition to unions ('a + 'b), this would look much less messy! ↩︎

  4. just lifetime bounds ↩︎

  5. Maybe I should have called it 'scope instead of 'this at least. ↩︎

  6. straight up counterfactual any way I've interpreted it ↩︎

Oh, I'm sorry if I wasn't clear - that was exactly my intention for most of my previous post: reword what you wrote in a way I would explain it to someone else in order to confirm my understanding (or lack thereof.) It's my attempt to decrease chances of misunderstanding because I don't know a better way.

In other words, the intention wasn't to provide new information or opposition, it was to confirm I really understood your previous explanation.

Well, one thing I learned (with software generally, not with Rust specifically) is not to rely on future features. (Not elaborating because that's getting really OT.)

And with Rust specifically, I already encountered many problems which clean solution depends on a future feature, but some of relevant tickets are already a decade old, so I'm just trying my best with what we currently have, i.e. focus on what's possible today. Of course, I understand that development of such software is enormous task.

Yes, that's what I meant. I understand and agree that my rewording is flawed, sorry about that.

That sounds like good methodology, I'll try to keep in in mind for next time, thanks.

No problem, that's my conclusion as well. At some point, I got the feeling that learning Rust is very similar to Go in a way - basics (Go rules, Rust syntax) are very easy, but learning what it actually implies is long endeavor (multi-generational in case of Go) which requires both studying theory and practical experience.

For me, takeaways are:

  • Consider merging lifetimes for different references again.
  • Consider what you wrote above - try to make capturing undesired lifetimes logically impossible.

I believe that keeping these in mind is going to be helpful - just merely being aware of a possibility means it's a tool to consider when solving a problem.

(I think that's the exact passage I learned to use shared lifetimes for unrelated references before I burned myself by using it wrongly.)

I actually read about variance in one of the learning materials, twice. But I failed to properly remember it.