Start learning free

LESSON 134 OF 414 · LOOPS & CONDITIONALS

Print Positive Numbers From Array in Rust: Looping Over &Vec

Practice Read the full explanation

Given an array of integers, print to the console the positive numbers, one on each line.

A number n is positive if it is strictly greater than 0.

Example:

Input: nums = [3, -2, 0, 4, -4]
Output (console):
3
4

Note: You have to print the numbers to the console, your function shouldn't return anything.


STEP 1 OF 3
    Ctrl + Enter to check

    RUST · LOOPS & CONDITIONALS

    Print Positive Numbers From Array in Rust, explained

    Problem overview

    The function print_positive_numbers receives a vector of integers, nums. It prints every positive number, one per line, in the order they appear, and returns nothing. A number is positive when it is strictly greater than 0, so zero doesn't count.

    For nums = [3, -2, 0, 4, -4] the output is:

    3
    4
    

    The -2 and -4 are negative, and 0 is neither positive nor negative, so those three are skipped.

    Approach

    Every element has to be looked at once, and each one gets the same question: is it greater than 0? If yes, print it, and if not, do nothing. That is a loop with an if inside. There is no need to build a new vector or to remember anything between elements. Printing is the whole result.

    Step by step

    1. Loop over &nums. The & matters. It lends the vector to the loop instead of giving it away. The loop variable num then stands for a reference to each element, a &i32.
    2. Test the value. Because num is a reference, *num reads the integer it points to. The condition is *num > 0, strictly greater, so 0 is excluded.
    3. Print inside the if. println!("{}", num) writes the value and a line break. Printing the elements that fail the test would be a mistake, so the println! belongs inside the braces of the if.

    The solution in Rust

    impl Solution {
        fn print_positive_numbers(nums: Vec<i32>) {
            for num in &nums {
                if *num > 0 {
                    println!("{}", num);
                }
            }
        }
    }
    

    The Rust details behind those few lines:

    • for num in nums versus for num in &nums. Without the &, the loop takes ownership of the vector and hands out the i32 values themselves. This also compiles, and in this function nothing needs nums afterwards. But in code that uses the vector again after the loop, the by-value form stops the build with an error about borrowing a moved value. Looping over &nums is the habit that keeps the vector usable.
    • Why the *. Writing if num > 0 with a &i32 doesn't compile: the compiler reports mismatched types, expected a reference and found an integer. Rust won't compare a reference with a plain number, so you dereference with *num.
    • Why println! needs no *. Formatting a reference prints the value it points to, so num and *num print the same text.
    • The function takes a Vec<i32> by value. The caller gives the vector away when it calls the function. That is the signature the lesson uses, and the loop over &nums is about what happens inside.

    Complexity

    Time: O(n) for a vector of length n. Each element is compared once and printed at most once.

    Space: O(1) extra. The function only holds a reference to the current element.

    Edge cases and common mistakes

    • Zero. Using >= instead of > would print the 0 in the example. Zero isn't positive.
    • An empty vector. The loop body never runs and nothing is printed, which is correct.
    • No positive numbers. For [-5, 0, -1] nothing is printed.
    • Returning instead of printing. The function has no return type. It should print each number, not collect them.
    • Forgetting the dereference. if num > 0 is rejected by the compiler. Use *num > 0.
    • Printing outside the if. A println! placed after the closing brace of the if prints every element, not only the positive ones.

    Testing

    • [3, -2, 0, 4, -4] prints 3 and 4.
    • [1, 2, 3] prints 1, 2 and 3.
    • [-1, -2, 0] prints nothing.
    • [] prints nothing.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free