Standard macros and format syntax
Quick answer
Macros accept token-based input and expand during compilation. Standard formatting macros make it convenient to build strings, print values and diagnose failures.
Choose formatting behavior
format! creates a String, while println! writes a line to standard output. {} uses Display; {:?} uses Debug. Named arguments, width, precision and escaped braces are supported by the format syntax. Use write! to write formatted data to a destination implementing the appropriate write trait.
fn main() { let name = "Ada"; let score = 9; let report = format!("{name}: {score:03}"); println!("{report}");}Expected stdout (not executed):
Ada: 009The width is a minimum, and the zero flag pads the number.
use std::fmt::Write;fn main() { let mut s = String::new(); write!(&mut s, "{{value: {:.2}}}", 1.25).unwrap(); println!("{s}");}Expected stdout (not executed):
{value: 1.25}Double braces emit literal braces rather than placeholders.
Common mistake
Do not treat Debug output as a stable wire format.
Try it yourself
Format a quantity with minimum width five and a separate price with two decimal places.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Standard macros and format syntax — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
You need formatted text for later storage, not immediate terminal output. Which macro fits?
Standard macros and format syntax — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let name = "Ada"; let score = 9; let report = format!("{name}: {score:03}"); println!("{report}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Standard macros and format syntax — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::fmt::Write; fn main() { let mut s = String::new(); write!(&mut s, "{{value: {:.2}}}", 1.25).unwrap(); println!("{s}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.