Printing is handled by a series of macros defined in std::fmt some of which are:
format!: write formatted text to String
print!: same as format! but the text is printed to the console (io::stdout).
println!: same as print! but a newline is appended.
eprint!: same as print! but the text is printed to the standard error (io::stderr).
eprintln!: same as eprint! but a newline is appended.
{} — Display formatter
Used for user-friendly output
Requires the Display trait.
fn main() {
println!("{}", 10);
println!("{}", "Rust");
}
Output
10
Rust
✔ Clean
✔ No quotes
✔ Best for UI / logs shown to users
2️⃣ {:?} — Debug formatter
Used for developer debugging
Requires the Debug trait.
Code
fn main() {
let v = vec![1, 2, 3];
println!("{:?}", v);
}
Output
[1, 2, 3]
✔ Shows internal structure
❌ Not user-friendly
3️⃣ {:#?} — Pretty Debug formatter
Same as Debug, but formatted nicely
Code
fn main() {
let v = vec![1, 2, 3];
println!("{:#?}", v);
}
Output
[
1,
2,
3,
]
✔ Excellent for inspecting complex data
4️⃣ {:x} — Lowercase hexadecimal
Code
fn main() {
println!("{:x}", 255);
}
Output
ff
5️⃣ {:X} — Uppercase hexadecimal
Code
fn main() {
println!("{:X}", 255);
}
Output
FF
6️⃣ {:b} — Binary format
Code
fn main() {
println!("{:b}", 10);
}
Output
1010
7️⃣ {:o} — Octal format
Code
fn main() {
println!("{:o}", 10);
}
Output
12
8️⃣ {:p} — Pointer address
Shows memory address
Code
fn main() {
let x = 10;
println!("{:p}", &x);
}
Output (example)
0x7ffddc3a9c2c
✔ Useful for debugging references & memory
9️⃣ {:e} / {:E} — Scientific notation
Code
fn main() {
println!("{:e}", 1234.56);
println!("{:E}", 1234.56);
}
Output
1.23456e3
1.23456E3
🔟 Width & alignment formatting
Right-aligned (default)
println!("{:5}", 42);
Output:
42
Left-aligned
println!("{:<5}", 42);
Output:
42
Center-aligned
println!("{:^5}", 42);
Output:
42
1️⃣1️⃣ Padding with zeros
Code
fn main() {
println!("{:05}", 42);
}
Output
00042
1️⃣2️⃣ Precision (floats & strings)
Float precision
fn main() {
println!("{:.2}", 3.14159);
}
Output:
3.14
String precision (truncate)
fn main() {
println!("{:.3}", "RustLang");
}
Output:
Rus
1️⃣3️⃣ Positional arguments
Code
fn main() {
println!("{1} is learning {0}", "Rust", "Alice");
}
Output
Alice is learning Rust
1️⃣4️⃣ Named arguments
Code
fn main() {
println!("{name} is {age} years old", name="Bob", age=30);
}
Output
Bob is 30 years old
1️⃣5️⃣ Mixing format styles
Code
fn main() {
println!("{name:?} scored {:04}", name="Alice", 7);
}
Output
"Alice" scored 0007
Top comments (0)