Start learning free

LESSON 165 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V1 - Single Item Total in Rust

Practice

Practice variables, arithmetic, and string concatenation by printing a tiny one-item receipt.

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

let item = "Coffee Mug";
let price = 12;
let quantity = 3;

Build:

Coffee Mug x3
Total: $36

Rules:

  • Compute total = price * quantity.
  • First line: "<item> x<quantity>" (e.g. "Coffee Mug x3").
  • Second line: "Total: $<total>".
  • Join the two lines with a newline "\n" into one string result, then print it with println!("{}", result).

Use format!("{} x{}", item, quantity) and format!("Total: ${}", total) to build strings from values.

format!("{}\n{}", line1, line2) joins both lines into one String.

        let item = "Coffee Mug";
        let price = 12;
        let quantity = 3;
        let total = price * quantity;
        let line1 = format!("{} x{}", item, quantity);
        let line2 = format!("Total: ${}", total);
        let result = format!("{}\n{}", line1, line2);
        println!("{}", result);

STEP 1 OF 8
    Ctrl + Enter to check

    Shopping Cart V1 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free