Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid obfuscating logic in a `loop`?

Tags:

rust

Trying to respect Rust safety rules leads me to write code that is, in this case, less clear than the alternative.

It's marginal, but must be a very common pattern, so I wonder if there's any better way.

The following example doesn't compile:

async fn query_all_items() -> Vec<u32> {
    let mut items = vec![];
    let limit = 10;

    loop {
        let response = getResponse().await;

        // response is moved here
        items.extend(response);

        // can't do this, response is moved above
        if response.len() < limit {
            break;
        }
    }

    items
}

In order to satisfy Rust safety rules, we can pre-compute the break condition:

async fn query_all_items() -> Vec<u32> {
    let mut items = vec![];
    let limit = 10;

    loop {
        let response = getResponse().await;

        let should_break = response.len() < limit;

        // response is moved here
        items.extend(response);

        // meh
        if should_break {
            break;
        }
    }

    items
}

Is there any other way?

like image 574
doplumi Avatar asked Oct 22 '25 00:10

doplumi


1 Answers

I agree with Daniel's point that this should be a while rather than a loop, though I'd move the logic to the while rather than creating a boolean:

let mut len = limit;
while len >= limit {
    let response = queryItems(limit).await?;

    len = response.len();

    items.extend(response);
}
like image 98
Rob Napier Avatar answered Oct 24 '25 13:10

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!