Why does this not pass the borrow checker

⚓ Rust    📅 2026-07-19    👤 surdeus    👁️ 3      

surdeus

I have the following code in an appropriate impl block:

fn get_free_segment(&mut self) -> &mut AllocatorSegment {
  if let Some(a) = self.segments.iter_mut().find(|s| !s.in_use()) {
    return a;
  }
  todo!(
    "handle metadata oom, {} segments in use",
    self.segments.iter().filter(|s| s.in_use()).count()
  );
}

The self.segments is a &'static mut [AllocatorSegment].

The borrow checker rejects this code because of the immutable borrow of self.segments on line 6 of the function, because it was previously mutably borrowed on line 1.

But the reference is either returned on line 2 (line 6 is not reached) or dropped on line 3 (no longer borrowed on line 6).
I don't quite understand what the borrow checker is complaining about in this case.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed