Mutable borrows in loops

⚓ Rust    📅 2025-04-28    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 115 days ago. The information described in this article may have changed.

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Mutable borrows in loops

I have a question about mutable borrows in loops. I have a couple of methods like so:

struct Foo {
    number: i32,
}

impl Foo {
    pub fn incr_and_ret(&mut self) -> &i32 {
        self.number += 1;
        &self.number
    }
    
    pub fn incr_to_10(&mut self) -> &i32 {
        loop {
            match self.incr_and_ret() {
                v @ 10 => break v,
                _ => {}
            }
        }
    }
}

Here's a link to the playground: Rust Playground

The main idea is, I have a function that mutates the internal state of Foo, and then returns a reference to something within Foo. Then, I'd like to call that multiple times, until the returned value meets a condition. This code does not compile, as the break v wants to borrow self, but self was already borrowed in the previous iteration of the loop.

I can't figure out how to do this without reworking my incr_and_ret method. In my actual code, incr_and_ret reads from a TCP stream, and so I'd like to modify internal state, while returning something unique to that call.

So my question has two parts: firstly, why is this disallowed? I cannot figure out why my borrow is being held between iterations of the loop. And secondly, is this possible right now? Or do I need to restructure my code?

3 posts - 3 participants

Read full topic

🏷️ rust_feed