Why doesn't the lifetime for this borrow end early?

⚓ Rust    📅 2026-03-27    👤 surdeus    👁️ 1      

surdeus

Hello, I have a question about lifetimes.

I have the following code:

fn find_or_default_mut<'a, T, P>(
  xs : &'a mut Vec<T>,
  mut pred : P,
  default : T,
) -> &'a mut T
  where P: FnMut(&T) -> bool
{
  let res = xs.iter_mut().find(|x| pred(&**x));
  if let Some(this_x) = res {
    this_x
  } else {
    xs.push(default);
    xs.last_mut().expect("just pushed")
  }
}

which should be safe, as the borrow of xs via res finishes before we start using xs again in the else branch. But this does not pass the borrow checker.

It was my understanding that non-lexical lifetimes was supposed to solve situations such as these. Why isn't it doing so here? Is it just an incompleteness in the borrow checker, or have I overlooked something?

Thanks!

3 posts - 3 participants

Read full topic

🏷️ Rust_feed