0
0
Rustprogramming~20 mins

Formatting output in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Formatting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Rust code using format! macro?

Consider the following Rust code snippet that formats a floating-point number:

let pi = 3.14159;
let formatted = format!("{:.2}", pi);
println!("{}", formatted);

What will be printed?

Rust
let pi = 3.14159;
let formatted = format!("{:.2}", pi);
println!("{}", formatted);
A3.14
B3.14159
C3.1
D3
Attempts:
2 left
๐Ÿ’ก Hint

Look at the format specifier {:.2}. It controls the number of decimal places.

โ“ Predict Output
intermediate
2:00remaining
What is the output of this Rust code using println! with padding?

What will this Rust code print?

let num = 42;
println!("{:>5}", num);
Rust
let num = 42;
println!("{:>5}", num);
A43
B 42
C41
D84
Attempts:
2 left
๐Ÿ’ก Hint

The {:>5} means right-align in a field of width 5.

๐Ÿ”ง Debug
advanced
2:00remaining
Why does this Rust code cause a compile error?

Examine this Rust code:

let name = "Alice";
println!("Hello, {:10}", name);

It causes a compile error. Why?

Rust
let name = "Alice";
println!("Hello, {:10}", name);
AThe format specifier {:10} is valid and code compiles without error.
BThe format specifier {:10} is missing alignment character, causing a compile error.
CThe format specifier {:10} is invalid for &str, causing a compile error.
DThe format specifier {:10} is valid, but the code is missing a semicolon.
Attempts:
2 left
๐Ÿ’ก Hint

Check if the format specifier works with strings in Rust.

โ“ Predict Output
advanced
2:00remaining
What is the output of this Rust code using named arguments in format string?

What will this Rust code print?

let width = 6;
let height = 4;
println!("Rectangle: {w} x {h}", w=width, h=height);
Rust
let width = 6;
let height = 4;
println!("Rectangle: {w} x {h}", w=width, h=height);
ARectangle: 4 x 6
BRectangle: {w} x {h}
CRectangle: 6 x 4
DRectangle: width x height
Attempts:
2 left
๐Ÿ’ก Hint

Look at how named arguments are passed to println!.

๐Ÿง  Conceptual
expert
3:00remaining
How does Rust's formatting traits affect output customization?

Rust uses traits like Display and Debug to control output formatting. Which statement best describes their difference?

A<code>Display</code> and <code>Debug</code> are interchangeable and produce the same output.
B<code>Display</code> formats output as JSON; <code>Debug</code> formats as XML.
C<code>Display</code> is only for numbers; <code>Debug</code> is only for strings.
D<code>Display</code> is for user-facing output; <code>Debug</code> is for developer debugging output.
Attempts:
2 left
๐Ÿ’ก Hint

Think about when you want pretty output for users vs detailed info for debugging.