James Smith
James Smith

Reputation: 329

How to iterate over a vector and compare the elements without using a clone to prevent a borrow error

This is my working code where things is a Vec<[u8 ; 32]>

let t_copy = tx.things.clone();

for (index, value) in tx.things.into_iter().enumerate() {
    if tx.id == value {
        return Err(CustomError);
    }
    if t_copy[index].max(t_copy[index+1]) == t_copy[index]  {
        return Err(CustomError);
    }

}

I use into_iter rather than iter as I compare the values here: tx.id == tx_parent

The above works but only because I clone the vector first which doesn't seem ideal to me. Is there a better way to achieve my goal here? Without the clone.

The purpose of the above code is to check the elements are in a certain order.

Upvotes: 0

Views: 1515

Answers (1)

user11877195
user11877195

Reputation:

Use iter, not into_iter, the former returns iterator that iterates over existing vector by borrowing it, the latter consumes data - takes ownership of the object, and directly turns it into iterator, which is not what you want.

Upvotes: 2

Related Questions