Start learning free

LESSON 88 OF 414 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating abs() in Rust: if and else

Practice Read the full explanation

The absolute value function (abs() in many languages) returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.

Create your own function that recreates this functionality, using the name and parameter n from the starter code.

Examples:

abs(-12) ➞ 12

abs(-544) ➞ 544

abs(250) ➞ 250

abs(0) ➞ 0

abs(-14) ➞ 14

Note:

Do not use the absolute value function provided by Rust (it will defeat the purpose of the challenge)


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 positive.
STEP 1 OF 3
    Ctrl + Enter to check

    RUST · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Abs in Rust, explained

    Problem overview

    The function abs takes an i32 called n and returns its absolute value: the distance from zero, always zero or positive. For a negative number that means dropping the minus sign, and for zero or a positive number it means returning the number unchanged. The lesson asks you to write this yourself instead of calling the standard library's version.

    Some results: abs(-5) is 5, abs(250) is 250 and abs(0) is 0.

    Approach

    There are only two cases, so one comparison settles everything. If n is below zero, flip its sign. Otherwise leave it alone. Negating a negative number gives a positive one: -(-5) is 5. Zero doesn't need flipping, and sending it down the "unchanged" path is correct because the absolute value of 0 is 0.

    Step by step

    1. Test for a negative number. Write an if with the condition n < 0. Rust needs no parentheses around the condition, and adding them compiles but triggers a warning. The braces are required.
    2. Return the negation. Inside the if, return -n; hands back the positive value.
    3. Handle everything else. An else branch returns n itself. Write } else { on one line, right after the closing brace of the if body.

    The solution in Rust

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

    A few Rust details:

    • The signature. n: i32 is a 32-bit signed integer, and -> i32 says the function returns one. Because the type is an integer, the function handles whole numbers only.
    • if is an expression. In Rust an if/else produces a value, so the same function can be written without any return: if n < 0 { -n } else { n } as the last line of the body. With no semicolon after it, that value becomes the function's result. Both forms behave identically.
    • Both branches must give the same type. In the expression form, -n and n are both i32. An if whose branches produce different types doesn't compile.
    • The standard library already has this. Integer types have an abs method, written n.abs(). The lesson's function is called abs too, but it is an associated function of Solution and is called as Solution::abs(n), so there is no clash.

    Edge cases and common mistakes

    • Zero. abs(0) takes the else branch and returns 0. Using n <= 0 as the condition also works, since -0 is 0, but it does needless work.
    • The most negative i32. An i32 holds values from -2147483648 to 2147483647, so 2147483648 has no i32 form. With n equal to i32::MIN, -n doesn't fit. In the optimized build the lessons use, the negation wraps silently and abs returns -2147483648. In a debug build the same negation panics with an overflow error. Ordinary inputs never reach this case.
    • Forgetting the return. Without return and without a final expression, the function body produces () instead of an i32, and the compiler reports mismatched types. In the expression form, adding a semicolon after the if/else block causes the same error.
    • Writing else if by accident. A second condition such as else if n >= 0 works but is redundant: if the first test failed, n is already non-negative.
    • Using decimals. The parameter is an i32, so inputs like -0.14 don't fit. For floating-point numbers the same logic works with an f64 parameter and 0.0 in the comparison. One quirk: negative zero, -0.0, is not less than 0.0, so the function returns it unchanged and it prints as -0.

    Testing

    • n = -5 gives 5.
    • n = 7 gives 7.
    • 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