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
- Test for a negative number. Write an
ifwith the conditionn < 0. Rust needs no parentheses around the condition, and adding them compiles but triggers a warning. The braces are required. - Return the negation. Inside the
if,return -n;hands back the positive value. - Handle everything else. An
elsebranch returnsnitself. Write} else {on one line, right after the closing brace of theifbody.
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: i32is a 32-bit signed integer, and-> i32says the function returns one. Because the type is an integer, the function handles whole numbers only. ifis an expression. In Rust anif/elseproduces a value, so the same function can be written without anyreturn: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,
-nandnare bothi32. Anifwhose branches produce different types doesn't compile. - The standard library already has this. Integer types have an
absmethod, writtenn.abs(). The lesson's function is calledabstoo, but it is an associated function ofSolutionand is called asSolution::abs(n), so there is no clash.
Edge cases and common mistakes
- Zero.
abs(0)takes theelsebranch and returns0. Usingn <= 0as the condition also works, since-0is0, but it does needless work. - The most negative
i32. Ani32holds values from-2147483648to2147483647, so2147483648has noi32form. Withnequal toi32::MIN,-ndoesn't fit. In the optimized build the lessons use, the negation wraps silently andabsreturns-2147483648. In a debug build the same negation panics with an overflow error. Ordinary inputs never reach this case. - Forgetting the return. Without
returnand without a final expression, the function body produces()instead of ani32, and the compiler reports mismatched types. In the expression form, adding a semicolon after theif/elseblock causes the same error. - Writing
else ifby accident. A second condition such aselse if n >= 0works but is redundant: if the first test failed,nis already non-negative. - Using decimals. The parameter is an
i32, so inputs like-0.14don't fit. For floating-point numbers the same logic works with anf64parameter and0.0in the comparison. One quirk: negative zero,-0.0, is not less than0.0, so the function returns it unchanged and it prints as-0.
Testing
n = -5gives5.n = 7gives7.n = 0gives0.n = -1gives1.
