Start learning free

LESSON 81 OF 414 · CONDITIONAL STATEMENTS

Reducing If Else To Boolean Expression in Rust

Practice Read the full explanation

We will learn a simple trick to improve our code quality: Reducing If-Else to Boolean Expressions.

Video Lesson:

STEP 1 OF 1
    Ctrl + Enter to check

    RUST · CONDITIONAL STATEMENTS

    Reducing If Else To Boolean Expression in Rust, explained

    Problem overview

    The function legal_age takes an age and returns a bool: true when the person is 18 or older and false otherwise. The starter code is empty, but the lesson is about a common first draft of this function and how to shorten it.

    Approach: the comparison is already a boolean

    A first draft usually looks like this:

    fn legal_age(age: i32) -> bool {
        if age >= 18 {
            return true;
        } else {
            return false;
        }
    }
    

    It works, but it says the same thing twice. The expression age >= 18 already evaluates to true or false. The if inspects that value only to produce the same value again. When the condition is true the function returns true, and when it is false it returns false, so the condition itself is the answer.

    Any comparison (==, !=, <, <=, >, >=) is an expression with a bool value, and so is anything built from them with &&, || and !. An expression like that can be returned, stored in a variable or passed to a function, just like a number.

    Why the longer form is worth avoiding

    Beyond the extra lines, the long form invites mistakes. Every added line is one more place to return the wrong literal, and a reader has to check both branches to be sure the function does what its name says. With return age >= 18; there is one line and one rule to verify. The shorter version also describes the function the way you would say it aloud: "it returns whether the age is at least 18."

    Step by step

    1. Drop the if and the else. They only repeat the value of the condition.
    2. Return the comparison. Write age >= 18 after return. The function's return type is bool, which is what the comparison produces, so the types match without any conversion.

    The solution in Rust

    impl Solution {
        fn legal_age(age: i32) -> bool {
            return age >= 18;
        }
    }
    

    Rust details worth knowing:

    • Inclusive boundary. The operator is >=, so exactly 18 counts. legal_age(18) is true, legal_age(17) is false, and legal_age(40) is true.
    • The idiomatic form. In Rust the last expression of a function, written without a semicolon, is its return value. So the body can be just age >= 18, with no return. The lesson uses an explicit return with a semicolon, which is also valid. Do not mix the two up: age >= 18; with a semicolon and no return makes the body evaluate to nothing, and the compiler reports a type mismatch.
    • No parentheses needed. The comparison >= binds tighter than return and the semicolon, so nothing extra is required.

    A second example

    The same reduction applies to any function that answers a yes-or-no question. A function that checks whether a number is even can return n % 2 == 0 directly, and one that checks whether two values differ can return a != b. If the long version of such a function has an if whose branches return only true and false, the condition can replace the whole statement.

    Complexity

    Time and space are both O(1): one comparison and no extra storage.

    Edge cases and common mistakes

    • Using > instead of >=. That makes 18 return false.
    • Returning the opposite. If the question is reversed, for example "is this person a minor?", return age < 18, or negate a condition with !. Do not write if cond { false } else { true }; !cond says the same in less space.
    • The shortcut is only for boolean results. If the two branches return different non-boolean values, such as two strings, you still need the if/else. The trick applies when the branches return true and false.
    • Negative ages. The comparison treats them like any other number: legal_age(-5) is false.

    Testing

    • age = 17 gives false.
    • age = 18 gives true.
    • age = 40 gives true.
    • age = 0 gives false.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free