Rust Tutorial: Output and Formatting in Rust
Master println!, print!, debug formatting, number precision, and padding in Rust.
Print Macros
| Macro | Newline | Use case |
|-------|---------|----------|
| `println!(fmt, …)` | Yes | Most common — print + newline |
| `print!(fmt, …)` | No | Print without newline |
| `eprintln!(fmt, …)` | Yes | Print to stderr |
| `format!(fmt, …)` | — | Build a `String` (no print) |
---
Placeholders
| Placeholder | Meaning |
|-------------|---------|
| `{}` | Default display |
| `{:?}` | Debug output |
| `{:#?}` | Pretty-print debug |
| `{:.2}` | Float with 2 decimal places |
| `{:>10}` | Right-align in 10 chars |
| `{:<10}` | Left-align in 10 chars |
| `{:^10}` | Center in 10 chars |
| `{:0>5}` | Zero-pad to 5 chars |
---
Named and Positional Arguments
```rust
let name = "Alice";
let age = 30;
println!("{name} is {age} years old"); // Rust 1.58+
println!("{0} is {1} years old", name, age); // positional
```
---
Debug Formatting
Any type that derives `Debug` can be printed with `{:?}`:
```rust
let point = (1, 2, 3);
println!("{:?}", point); // (1, 2, 3)
println!("{:#?}", point); // pretty-printed
```
---
Number Formatting
```rust
let result = 22.0_f64 / 7.0;
println!("{:.2}", result); // 3.14
println!("{:.4}", result); // 3.1429
println!("{:08.2}", result); // 00003.14 (zero-padded width 8)
```
---
Padding and Alignment
```rust
println!("{:<10}", "left"); // "left "
println!("{:>10}", "right"); // " right"
println!("{:^10}", "center"); // " center "
println!("{:-^10}", "hi"); // "----hi----"
```
---
What's Next?
You can now format Rust output precisely. Next: **control flow** — if/else, match expressions, and pattern matching.
What you'll learn in this Rust output and formatting in rust tutorial
This interactive Rust tutorial has 5 hands-on exercises. Estimated time: 15 minutes.
- println! and print! — Use `println!` to print with a newline and `print!` to print without one. Print `Hello` with `print!`, then `World` with…
- Named and Positional Arguments — Rust format strings support positional `{0}` and named `{name}` arguments. Print `"Alice is 30 years old"` using named a…
- Debug Formatting — Use `{:?}` (or `{:#?}` for pretty-print) to debug-print values that implement `Debug`. Print the tuple `(1, 2, 3)` using…
- Number Formatting — Control float precision with `{:.2}`. Compute `22.0_f64 / 7.0` and print the result rounded to 2 decimal places.
- Padding and Alignment — Use `{:<10}` for left-align, `{:>10}` for right-align, and `{:^10}` for center — all in a field of 10 characters. Print …
Rust Output and Formatting in Rust concepts covered
- Print Macros
- Placeholders
- Named and Positional Arguments
- Debug Formatting
- Number Formatting
- Padding and Alignment
- What's Next?