Add boolean condition to a for loop

Hi, I'm new to the Rust language and I'm doing a simple local search algorithm for a project. I need to iterate over a vector and generate neighbors until I find a better one or reach the end. In C++, a for loop with a stop condition would fit for me, but since Rust for loops are differente I don't know if there is a similar tool I could use. I'm sure the answer is simple, but I haven't found it yet.

Thanks in advance.

If you need a C-like loop in Rust:

for(int i=0; i < end; i++)


for i in 0..end {

If you need to modify i during the loop, you have to use let mut i=0; while i < end { i += 1' } instead.

However, the idiomatic way to iterate a vector is:

for item in vec.iter() {

or if you need the index:

for (i, item) in vec.iter().enumerate() {
1 Like

You can exit the for loop early using break. But instead of copying the code as-is, try to leverage Rust's iterators to do the job in a more natural way. For example, you can use find to find the first element matching the condition:

if let Some(element) = vec.iter().find(|x| x > a) {

1 Like

Thanks! I was looking for another option that wasn't using break, but I suppose that's the idea.

About iterators, I will use them more often. Guess I'm too used to C-like and working with the index :sweat_smile:

Since you are working with neighbors you might be interested in the .windows(3) method for slices.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.