Start learning free

LESSON 103 OF 293 · CONDITIONAL STATEMENTS - CHALLENGES

Top K Brands V2 in Rust: Picking the Better of Two Brands

Practice Read the full explanation

Two brands sell the same product. Show the one with the higher rating.

You start with: an empty editor (no starter code). Declare this data yourself:

let brand1 = "TechPro";
let rating1 = 4;
let brand2 = "MegaCorp";
let rating2 = 5;

Build:

1. MegaCorp (5)

Rules:

  • Use if/else to pick the winner: brand1 when rating1 > rating2, otherwise brand2.
  • Declare best_brand and best_rating without a value (let best_brand;) and assign them in the branches.
  • Format the result as "1. Brand (rating)" and print it with println!(...).

Pick the winner into best_brand and best_rating first, then build the output text from them.

format!("1. {} ({})", brand, rating) builds text from several values, numbers included.

        let brand1 = "TechPro";
        let rating1 = 4;
        let brand2 = "MegaCorp";
        let rating2 = 5;
        let best_brand;
        let best_rating;
        if rating1 > rating2 {
            best_brand = brand1;
            best_rating = rating1;
        } else {
            best_brand = brand2;
            best_rating = rating2;
        }
        println!("1. {} ({})", best_brand, best_rating);

STEP 1 OF 11
    Ctrl + Enter to check

    RUST · CONDITIONAL STATEMENTS - CHALLENGES

    Top K Brands V2 in Rust, explained

    Problem overview

    Two brands sell the same product, each with a rating. The program shows the brand with the higher rating as the top entry, in the form 1. Brand (rating). The lesson starts with an empty editor, so you declare the data yourself: TechPro with rating 4 and MegaCorp with rating 5.

    MegaCorp's 5 beats TechPro's 4, so the output is:

    1. MegaCorp (5)
    

    The code has to work for any two ratings, not only these. The previous version printed a single brand. The new work is the decision between two.

    Approach: assign the winner in each branch

    The comparison is a single if/else. If rating1 is greater than rating2, brand 1 wins. In every other case brand 2 wins, including a tie. The statement fixes that tie rule: not strictly better means the second brand.

    The program has to remember two things about the winner, its name and its rating, so there are two variables, best_brand and best_rating. Both are declared before the if without a value. Each branch then assigns both, and one println! after the branches prints whichever brand won. This avoids writing the printing code twice.

    A more compact form

    In Rust, an if/else is an expression: it produces a value, the last expression of whichever branch ran. That lets you pick the whole pair at once and unpack it into two variables:

    let (best_brand, best_rating) = if rating1 > rating2 {
        (brand1, rating1)
    } else {
        (brand2, rating2)
    };
    println!("1. {} ({})", best_brand, best_rating);
    

    For the lesson's data this prints 1. MegaCorp (5), the same as the version with separate assignments. Both branches must produce a value of the same type, and the branches here end without a semicolon so their tuples become the value of the if. The lesson's steps use the other form, with two assignments per branch, which shows that a variable can be declared first and given its value later.

    Step by step

    1. Declare the data in four let statements: brand1 and rating1, then brand2 and rating2. Brands are text in quotes, and ratings are plain whole numbers.
    2. Declare the result variables: let best_brand; and let best_rating;, with no value yet.
    3. Write the condition. Open an if that checks rating1 > rating2. Inside it, assign best_brand = brand1;. There is no let here, because the variable already exists.
    4. Assign the rating in the same branch: best_rating = rating1;. The name and the rating travel together.
    5. Add the else and assign best_brand from brand2.
    6. Assign best_rating from rating2 in the else.
    7. Print the winner with a template that holds the rank 1. , the brand, a space and parentheses around the rating.

    The solution in Rust

            let brand1 = "TechPro";
            let rating1 = 4;
            let brand2 = "MegaCorp";
            let rating2 = 5;
            let best_brand;
            let best_rating;
            if rating1 > rating2 {
                best_brand = brand1;
                best_rating = rating1;
            } else {
                best_brand = brand2;
                best_rating = rating2;
            }
            println!("1. {} ({})", best_brand, best_rating);
    

    What to know about the Rust here:

    • A let without a value is allowed, but only once per path. The compiler accepts let best_brand; because each branch assigns it exactly once. The variable doesn't need mut, since it never changes after that single assignment.
    • Assigning twice is an error. If you assigned best_brand before the if and again inside it, the compiler would stop with cannot assign twice to immutable variable. Use let mut only if you really want to overwrite a value.
    • A missing branch is an error. An if without an else would leave best_brand unassigned on some paths, and reading it afterwards doesn't compile.
    • The types follow from the values. best_brand becomes a &str and best_rating an i32 once the compiler sees the assignments. Both print with {}.

    Edge cases and common mistakes

    • Ties. With ratings 4 and 4 the output is 1. MegaCorp (4), the second brand. Writing >= in the condition would give the first brand instead and break the tie rule.
    • The first brand winning. With ratings 5 and 3 the condition is true, and the output is 1. TechPro (5). The lesson's data only exercises the else branch, so it is worth checking this path as well.
    • Updating only one variable. If a branch sets the name but forgets the rating, the program doesn't compile. Mismatched pairs would otherwise print a brand with the wrong rating.
    • Wrong template. The text is 1. then the brand, a space, (, the rating and ). A missing space before the parenthesis fails the lesson's tests.
    • Mixed number types. Comparing values of different integer types, such as an i32 rating with an i64 one, doesn't compile, because Rust doesn't convert between them on its own. Both ratings here are plain literals, so both are i32 and the comparison is fine. A quoted 5 is text, so it can't be compared with a number either.
    • Hardcoding the answer. Printing 1. MegaCorp (5) directly matches the example, but the variables are there so the code works for other ratings too.

    Testing

    • Ratings 4 and 5 (TechPro and MegaCorp) print 1. MegaCorp (5).
    • Ratings 5 and 3 print 1. TechPro (5).
    • Ratings 4 and 4 print 1. MegaCorp (4).
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free