How to manually reduce a lifetime without closures ('a > 'b)

⚓ rust    📅 2025-07-16    👤 surdeus    👁️ 1      

surdeus

I need to reduce lifetimes with each subsequent calls. Here is a simple example what I want:

struct Stack<'a>(PhantomData<&'a mut ()>);

impl<'a> Stack<'a> {
    fn push<'b, T, F>(self, f: F) -> (Stack<'b>, &'b mut T)
    where
        'a: 'b,
        T: 'b,
        F: FnOnce() -> T,
    {
        todo!()
    }
}

fn example(stack: Stack) {
    let (stack, value0) = stack.push(|| 13);
    let (stack, value1) = stack.push(|| Vec::<&mut i32>::new());
    let (stack, value2) = stack.push(|| 42);

    value1.push(value0);
    value1.push(value2);
}

How I understand it:

  • 'a >= 'b, so Stack<'a> >= Stack<'b>
  • value0 is '1
  • value1 is '2
  • value2 is '3
  • '1 >= '2 >= '3
  • value1 should be able to store value0 (value0 outlives value1)
  • value1 should not be able to store value2 (value1 outlives value2)

But this example does compile. I can limit lifecycle with closures but this will make Stack unusable.

Can anyone help with this? What am I doing wrong? Is this some kind of hidden inference magic I'm now aware of?

7 posts - 3 participants

Read full topic

🏷️ rust_feed