Start learning free

LESSON 161 OF 414 · LOOPING OVER ARRAY INDICES

Continue In For Loops in Rust

Lesson Read the full explanation

With the continue statement we can stop the current iteration of the loop, and continue with the next.

When Rust hits continue, it skips (not execute) any code left, and jumps directly to the next iteration instead.

In this example, we will not let anyone inside a bar if their age is less than 21:

let ages = vec![10, 30, 21, 19, 25];

for age in ages {
	if age < 21 {
		continue;
	}
	println!("Someone of age {} entered the bar.", age);
}

The output of this program is:

Someone of age 30 entered the bar.
Someone of age 21 entered the bar.
Someone of age 25 entered the bar.

As you can see, our program doesn't print for ages 10 and 19.

Here's what happens during this loop:

1. First iteration:
	a. age = 10
	b. Is age < 21? Yes:
	    continue => Go directly to the next age

2. Second iteration:
	a. age = 30
	b. Is age < 21? No.
	c. println!

3. Third iteration:
	a. age = 21
	b. Is age < 21? No.
	c. println!

4. Fourth iteration:
	a. age = 19
	b. Is age < 21? Yes:
	    continue => Go directly to the next age

5. Fifth iteration:
	a. age = 25
	b. Is age < 21? No.
	c. println!

Assignment
Let's allow only the people with height at least 170 into the arena.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    RUST · LOOPING OVER ARRAY INDICES

    Continue In For Loops in Rust, explained

    What continue does

    The continue statement ends the current iteration of a loop and jumps to the next one. Any code below it in the loop body is skipped for that item. Where break leaves the loop completely, continue only skips one round. It is the natural way to say "ignore the items that don't qualify".

    An example

    This loop lets people into a bar only if they are at least 21:

    let ages = vec![10, 30, 21, 19, 25];
    
    for age in ages {
        if age < 21 {
            continue;
        }
        println!("Someone of age {} entered the bar.", age);
    }
    

    The output:

    Someone of age 30 entered the bar.
    Someone of age 21 entered the bar.
    Someone of age 25 entered the bar.
    

    For 10 and 19 the condition is true, so continue runs and the println! below it is skipped. For 30, 21 and 25 the condition is false, the if does nothing and execution falls through to the print. An age of exactly 21 is let in, because the test is < 21, not <= 21.

    Details that matter in Rust

    • References need a dereference. When you loop over &heights, each item is an &i32. Writing height < 170 doesn't compile: the compiler reports a type mismatch, expecting a reference and finding an integer. Write *height < 170 to compare the number the reference points to.
    • Printing needs no dereference. println!("{}", height) prints a reference exactly as it prints the number it points to.
    • Borrowing keeps the vector. for height in &heights borrows the vector, so you can still use heights after the loop, for example to call heights.len(). Looping over heights itself moves it into the loop.
    • Only the current iteration is skipped. After continue, the loop moves on to the next item. In nested loops it affects only the innermost loop.
    • A trap in while loops. In a while loop that increments its counter at the bottom, a continue placed before the increment jumps back to the condition without changing the counter, so the loop can repeat forever. A for over a range or a vector advances on its own, so this doesn't happen.
    • An alternative shape. Instead of skipping the unwanted items, you can put the wanted case in the if: if *height >= 170 { println!("{}", height); }. It behaves the same. continue reads better when the skipped case is a quick exception and the main work is long.

    The exercise

    The task is to let only people with a height of at least 170 into the arena, which here means printing their heights. The heights are 180, 139, 174, 190, 162.

    1. Declare the vector with vec![180, 139, 174, 190, 162] and bind it to heights.
    2. Loop over a reference to it. Write for height in &heights. The vector is borrowed rather than consumed, and each height is an &i32.
    3. Skip the short ones. Add if *height < 170 { continue; }. The * reads the number so it can be compared with 170.
    4. Print the rest. Below the if, println!("{}", height); runs only for heights of at least 170.
    let heights = vec![180, 139, 174, 190, 162];
    for height in &heights {
        if *height < 170 {
            continue;
        }
        println!("{}", height);
    }
    

    The output:

    180
    174
    190
    

    The heights 139 and 162 are skipped. The test < 170 means that a person exactly 170 tall would be let in, matching "at least 170".

    Key takeaways

    • continue skips the rest of the current iteration and starts the next one.
    • Put the skip condition before the code that should be skipped.
    • Dereference with * when you compare the items of a borrowed vector with plain numbers.
    • break ends the loop; continue only skips one item.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free