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?
let pi = 3.14159; let formatted = format!("{:.2}", pi); println!("{}", formatted);
Look at the format specifier {:.2}. It controls the number of decimal places.
The format specifier {:.2} rounds the floating-point number to 2 decimal places, so 3.14159 becomes 3.14.
What will this Rust code print?
let num = 42;
println!("{:>5}", num);let num = 42; println!("{:>5}", num);
The {:>5} means right-align in a field of width 5.
The number 42 is printed right-aligned in a space of 5 characters, so it has 3 spaces before it.
Examine this Rust code:
let name = "Alice";
println!("Hello, {:10}", name);It causes a compile error. Why?
let name = "Alice"; println!("Hello, {:10}", name);
Check if the format specifier works with strings in Rust.
The specifier {:10} means left-align in a field of width 10 (default for strings), which is valid for strings. The code compiles and prints "Hello, Alice ".
What will this Rust code print?
let width = 6;
let height = 4;
println!("Rectangle: {w} x {h}", w=width, h=height);let width = 6; let height = 4; println!("Rectangle: {w} x {h}", w=width, h=height);
Look at how named arguments are passed to println!.
The named arguments w and h are replaced by the values of width and height, so it prints "Rectangle: 6 x 4".
Rust uses traits like Display and Debug to control output formatting. Which statement best describes their difference?
Think about when you want pretty output for users vs detailed info for debugging.
Display is implemented for user-friendly output, while Debug is for detailed, programmer-focused output useful during debugging.