format! macro
- Rust course
- Beginner
- Lesson 22/115
- 4 min
Build a new String with the format! macro.
The format! macro
format! uses the same format string as println! but returns a String instead of printing:
let urun = "Kalem";
let adet = 3;
let fiyat = 12.5;
let line = format!("{urun} x{adet} = {:.2} TL", fiyat * adet as f64);
println!("{line}"); // Kalem x3 = 37.50 TLThe format string is checked at compile time and the arguments are borrowed, so the values can still be used afterwards.
Positional and named arguments
Arguments can be used in order, by number or by name:
format!("{0} {1} {0}", "a", "b"); // "a b a"
format!("{ad} {ad}", ad = "Ada"); // "Ada Ada"
format!("{:^7}", "ok"); // " ok "
format!("{:08.3}", 3.14159); // "0003.142"
format!("{:x} {:b}", 255, 5); // "ff 101"Practice Receipt line
Write fn line(urun: &str, adet: u32, fiyat: f64) -> String returning format!("{urun:<8}{adet:>3} x {fiyat:6.2}"). Print the result of line("Kalem", 3, 12.5) inside square brackets: println!("[{}]", ...).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn line(urun: &str, adet: u32, fiyat: f64) -> String {
format!("{urun:<8}{adet:>3} x {fiyat:6.2}")
}
fn main() {
println!("[{}]", line("Kalem", 3, 12.5));
}Expected output
[Kalem 3 x 12.50]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>format!("{:>5}", "ab")</code> produce?
- "ab "
- " ab "
- "ab"
- " ab" Correct answer
Explanation: > right-aligns and pads the 5-character field with spaces on the left; < left-aligns and ^ centers.
2 Produce text
let dosya = ____!("rapor-{}.csv", 2026);
let dosya = format!("rapor-{}.csv", 2026);
Explanation: format! returns the formatted text as a String.
3 Format and output
| Term | Meaning |
|---|---|
{:>5} "ab" |
" ab" |
{:05} 42 |
"00042" |
{:x} 255 |
"ff" |
{0}{0} "a" |
"aa" |