๐ Scenario: You are creating a simple Rust program to display product prices clearly for a small shop.
๐ฏ Goal: Learn how to format output in Rust using println! with placeholders and formatting options.
๐ What You'll Learn
Create a dictionary (HashMap) with product names and prices
Create a variable for a price threshold
Use a loop to print products with prices formatted to 2 decimal places
Print the formatted output lines
๐ก Why This Matters
๐ Real World
Formatting prices clearly is important in shops, invoices, and reports to make numbers easy to read and professional.
๐ผ Career
Many programming jobs require formatting output for user interfaces, reports, or logs, making this skill very useful.
Progress0 / 4 steps
1
Create the product prices HashMap
Create a HashMap called products with these exact entries: "Apple" with price 0.99, "Banana" with price 0.59, and "Cherry" with price 2.99.
Rust
Hint
Use HashMap::new() and insert to add each product and price.
2
Add a price threshold variable
Inside the main function, create a variable called threshold and set it to 1.00.
Rust
Hint
Use let threshold = 1.00; inside main.
3
Loop and format output
Use a for loop with variables product and price to iterate over products.iter(). Inside the loop, use println! to print each product and price formatted to 2 decimal places using {:.2}.
Rust
Hint
Use for (product, price) in products.iter() and println!("{}: ${:.2}", product, price);.
4
Print products above threshold
Modify the for loop to print only products with a price greater than threshold. Use println! to print the product name and price formatted to 2 decimal places.
Rust
Hint
Use an if statement inside the loop to check if *price > threshold.
Practice
(1/5)
1. What does the placeholder {} do in Rust's println! macro?
easy
A. It comments out the line in the code.
B. It inserts the value of a variable or expression into the string.
C. It creates a new variable inside the string.
D. It repeats the string multiple times.
Solution
Step 1: Understand the role of {} in formatting
The {} acts as a placeholder where Rust inserts the value of a variable or expression inside a string.
Step 2: Recognize its use in println!
When using println!("Hello, {}", name);, Rust replaces {} with the value of name.
Final Answer:
It inserts the value of a variable or expression into the string. -> Option B
Quick Check:
Placeholder {} = Insert value [OK]
Hint: Remember: {} means insert value here [OK]
Common Mistakes:
Thinking {} creates variables
Assuming {} repeats strings
Confusing {} with comments
2. Which of the following is the correct syntax to format a floating-point number with 2 decimal places in Rust?
Rust uses {:.2} inside println! to format a float with 2 decimal places.
Step 2: Check each option
println!("{:.2}", 3.14159); uses {:.2}, which is correct. Others use invalid or incorrect syntax.
Final Answer:
println!("{:.2}", 3.14159); -> Option A
Quick Check:
Decimal places = {:.2} [OK]
Hint: Use {:.N} to set N decimal places [OK]
Common Mistakes:
Using {2f} or {.2f} which is invalid in Rust
Omitting the colon before precision
Confusing with other language formats
3. What is the output of this Rust code?
let x = 255;
println!("Decimal: {}, Hex: {:x}, Binary: {:b}", x, x, x);
medium
A. Decimal: 255, Hex: FF, Binary: 11111111
B. Decimal: 255, Hex: ff, Binary: 1111111
C. Decimal: 255, Hex: 0xff, Binary: 11111111
D. Decimal: 255, Hex: ff, Binary: 11111111
Solution
Step 1: Understand formatting specifiers
{} prints decimal, {:x} prints lowercase hex, {:b} prints binary.
Step 2: Convert 255 to hex and binary
255 decimal is ff in hex (lowercase) and 11111111 in binary.
Final Answer:
Decimal: 255, Hex: ff, Binary: 11111111 -> Option D
Quick Check:
Hex lowercase = {:x}, Binary = {:b} [OK]
Hint: Use {:x} for hex lowercase, {:b} for binary [OK]
Common Mistakes:
Expecting uppercase hex without :X
Adding 0x prefix automatically
Miscounting binary digits
4. Identify the error in this Rust code snippet:
let num = 42;
println!("Number: {2}", num);
medium
A. The println! macro requires a semicolon inside the string.
B. The variable num is not declared correctly.
C. The placeholder {2} refers to an argument index that does not exist.
D. Rust does not support numbered placeholders.
Solution
Step 1: Check placeholder indexing
The placeholder {2} means use the third argument (index 2), but only one argument num is provided.
Step 2: Understand argument count mismatch
Since only one argument exists, index 2 is out of range, causing a runtime error.
Final Answer:
The placeholder {2} refers to an argument index that does not exist. -> Option C
Quick Check:
Placeholder index must match argument count [OK]
Hint: Count arguments before using numbered placeholders [OK]
Common Mistakes:
Using wrong index in placeholders
Assuming Rust auto-corrects missing arguments
Thinking semicolon needed inside string
5. You want to print a table of names and scores aligned in columns using Rust's formatting. Which code correctly aligns the names left in 10 spaces and scores right in 5 spaces?
let name = "Alice";
let score = 93;
// Which println! line is correct?
hard
A. println!("{:<10} | {:>5}", name, score);
B. println!("{:>10} | {:<5}", name, score);
C. println!("{:10} | {:5}", name, score);
D. println!("{:^10} | {:^5}", name, score);
Solution
Step 1: Understand alignment specifiers
{:<10} aligns left in 10 spaces, {:>5} aligns right in 5 spaces.
Step 2: Match alignment to requirements
Names should be left aligned, scores right aligned, so println!("{:<10} | {:>5}", name, score); matches perfectly.
Final Answer:
println!("{:<10} | {:>5}", name, score); -> Option A
Quick Check:
Left align = <, Right align = > [OK]
Hint: Use <: for left, >: for right alignment [OK]
Common Mistakes:
Swapping alignment symbols
Omitting width numbers
Using center alignment when not needed
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.