Start learning free

LESSON 77 OF 414 · CONDITIONAL STATEMENTS

Return Negative in Rust: if and Unary Minus

Practice Read the full explanation

Create a function that takes a number as an argument and returns negative of that number. Return negative numbers without any change.

Examples:

4 ➞ -4

15 ➞ -15

-4 ➞ -4

0 ➞ 0

Hints:

You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is not negative.
STEP 1 OF 3
    Ctrl + Enter to check

    RUST · CONDITIONAL STATEMENTS

    Return Negative in Rust, explained

    Problem overview

    The function negative takes an integer n and returns it as a negative number. If n is positive, the answer is its opposite. If n is already negative, it comes back unchanged. Zero stays zero.

    negative(4)  -> -4
    negative(15) -> -15
    negative(-4) -> -4
    negative(0)  -> 0
    

    This is easy to misread as "flip the sign". Flipping would turn -4 into 4, but the task asks for -4. The result is never positive.

    Approach

    Split the inputs into two groups by asking one question: is n less than zero?

    • If yes, the number is already negative and is returned as it is.
    • If no, n is zero or positive, and the unary minus -n gives the negative value. For zero, -0 is just 0, so the zero example works without special handling.

    In maths terms the result is minus the absolute value of n. The if-else spells out the same rule in steps.

    Step by step

    1. Write the if. Check n < 0. A true result means the input is already negative.
    2. Return n from inside the if. No change is needed in that case.
    3. Add the else and return -n. For zero or a positive number, putting a minus in front produces the negative value that is needed.

    The solution in Rust

    impl Solution {
        fn negative(n: i32) -> i32 {
            if n < 0 {
                return n;
            } else {
                return -n;
            }
        }
    }
    

    The Rust details worth knowing:

    • The signature. n: i32 is the parameter, and -> i32 declares that the function returns an i32. Without the arrow, the function would return () and the return statements would not compile.
    • return with a semicolon. Each branch leaves the function immediately with its value. This is correct, and it is how the lesson writes it.
    • An expression-style alternative. Rust functions return the value of their last expression, so you can drop return and the semicolons: if n < 0 { n } else { -n }. Both branches produce an i32, so the whole if-else is the function's result.
    • Unary minus. -n is allowed because i32 is signed. For an unsigned type such as u32 it would not compile.
    • The one special input. i32::MIN is negative, so it takes the if branch and returns as it is. Negating it would be a problem, because -i32::MIN doesn't fit in an i32: an optimised build wraps back to -2147483648, and a debug build panics. The else branch only sees zero and positive numbers, whose negation always fits, so the function never negates i32::MIN.

    Edge cases and common mistakes

    • Zero. It goes to the else branch and returns -0, which is 0 for integers. Integers have no negative zero.
    • Negating everything. Returning -n for all inputs fails on negative numbers: -(-4) is 4.
    • Using n <= 0. It still gives correct answers, because negating zero gives zero, but the check is not needed.
    • Using n > 0 for the negation. That works too, as long as the other branch returns n. What matters is that each input is handled by exactly one branch.
    • Forgetting the return type. Leaving out -> i32 gives a type error, since the function would be declared to return nothing.
    • Printing instead of returning. This function returns a value. The calling code reads the result, so printing it isn't enough.

    Testing

    • n = 4 gives -4.
    • n = 15 gives -15.
    • n = -4 gives -4.
    • n = 0 gives 0.
    • n = 1 gives -1.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free