Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 132 ยท Getting Started

Printing with println! and format!

Master Rust output - println!, print!, eprintln!, format!, write! and dbg!, placeholders, width, precision, alignment, fill, hex, binary and scientific formats, and Display versus Debug.

Every program needs to show results, and in Rust that means the formatting macros: println!, print!, format!, write! and friends. They all share one mini-language for describing how values should look: how wide a column is, how many decimals a number has, whether it is shown in hex, and whether a type is displayed for users or dumped for debugging. Learn the mini-language once and it works everywhere, including in error messages, logging and panic!.

This lesson covers the family of macros, placeholders and arguments, the format specifiers, and the two most important traits behind them: Display for human-readable output and Debug for programmer-readable output. These macros are used in every later lesson, so it is worth getting comfortable with them now. The next lesson goes in the other direction and reads input.

The printing macros

Rust has several macros that all take a format string and arguments:

Macro Where the text goes
println! Standard output, followed by a newline
print! Standard output, no newline
eprintln! / eprint! Standard error (for diagnostics and errors), with or without a newline
format! Returns a new String instead of printing
write! / writeln! Writes into anything that can receive text: a String, a file, a buffer, a formatter
panic! Prints a message to standard error and stops the thread
dbg! Prints an expression, its value and its source location to standard error, and returns the value

They are macros because the compiler checks your format string against the arguments at compile time. If the number of placeholders and arguments differs, or a type cannot be formatted that way, you get a compile error, never a run-time crash. Try it:

Rust A mismatched format string (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops with error: 3 positional arguments in format string, but there are 2 arguments, and underlines the placeholders and the arguments. Add the missing argument (5) and it compiles.

Stdout and stderr are two separate streams. On a terminal both show up on screen, but you can redirect them separately, which is why tools print results to stdout and diagnostics to stderr. Our editor shows stdout as the program output and stderr separately.

Rust print, println, eprintln and format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

println!() with no arguments just prints a newline. format! returns an owned String that you can store, return from a function or pass on. Note that output to stdout is usually line buffered: if you use print! for a prompt and want it to appear before the program waits for input, flush it with io::stdout().flush() (you will see this in Reading input).

Placeholders and arguments

A pair of braces {} in the format string is a placeholder. There are several ways to fill it.

Positional (in order): {} takes the next argument.

Numbered: , pick arguments by index, so you can reuse one or reorder.

Named: picks a named argument given as name = value.

Captured: with no matching named argument captures the variable name that is in scope. Since Rust 1.58 you can write the variable directly, which is the clearest form for simple cases.

Rust Four ways to fill a placeholder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

To print a literal brace, double it: {{ and }}. Captured identifiers work only for plain names, not for expressions: {cups * 2} is an error. Compute the value first (let doubled = cups * 2;) or pass it as an argument, {} with cups * 2 after the string.

Display and Debug

The most important choice in a placeholder is which trait formats the value:

  • {} uses the Display trait: the polished, user-facing representation. Numbers, strings and characters implement it. Many types do not: there is no default way to show a Vec or a struct to an end user, so println!("{}", vec) does not compile.
  • {:?} uses the Debug trait: a programmer-facing representation that exists for almost all standard types and that you can get for your own types with #[derive(Debug)].
  • {:#?} is pretty Debug: the same data spread over several indented lines. Excellent for nested structures.
Rust Display, Debug and pretty Debug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Compare the two string lines: Display shows plain, while Debug shows "plain" with quotes, and escapes special characters (a newline becomes \n), so you can see exactly what is inside. For user the derived Debug prints the type name and every field. The pretty form is long but readable, which is why {:#?} is the first tool you reach for when a nested value looks wrong.

If you try to print your own type with {} without implementing Display, the compiler refuses:

Rust No Display for a struct (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is E0277: `Point` doesn't implement `std::fmt::Display`, with a note that in format strings you may be able to use {:?} (or {:#?} for pretty-print) instead, if you implement Debug or add #[derive(Debug)]. Deciding what the user-facing text of Point is ((1, 2)? x=1,y=2?) is your job, and you do it by implementing Display, covered in Display and From.

Format specifiers

After a colon inside the braces you can add a format spec. The full grammar is {[argument]:[[fill]align][sign][#][0][width][.precision][type]}, but each part is optional, and a few patterns cover nearly all uses.

Width, alignment and fill

A number sets the minimum width. Text is left-aligned by default and numbers are right-aligned. Use < (left), ^ (center) or > (right) to choose, and put a fill character before the alignment:

Rust A small table with width and alignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The width can come from a variable with width$ (a captured variable named width) or from a positional argument with 1$. In the table, {:>8.2} means "right-aligned in 8 characters, with 2 decimals" for the price, and the fill/alignment {:-^6} of an empty string draws a rule of dashes. Counting is in chars of the text, so very wide Unicode characters (CJK, emoji) can still misalign columns in a terminal.

Precision

After a dot comes the precision. For floating-point numbers it is the number of decimals (rounded). For strings it truncates to that many characters.

Rust Precision and number formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that {:.0} of 2.5 gives 2: Rust rounds exact halves to the nearest even digit, like most languages' modern floating-point formatting. If you format money, remember that f64 cannot represent most decimal fractions exactly. Use integers of cents for real accounting.

Other types: hex, binary, octal, exponent

The last letter of the spec chooses the type. Plain {} is Display and ? is Debug, and these letters pick a numeric base or notation:

Spec Meaning Example (255)
{:x} Lowercase hexadecimal ff
{:X} Uppercase hexadecimal FF
{:b} Binary 11111111
{:o} Octal 377
{:e} Lowercase scientific notation 2.55e2
{:#x} # adds the prefix 0xff
{:#010b} Prefix, zero padding, width 10 0b11111111
Rust Hex, binary and scientific notation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The # flag adds 0x, 0b or 0o, and zero padding counts the prefix as part of the width, so {:#06x} gives six characters in total. Also see that Debug of a float always shows a decimal point (1.0), while Display prints 1 for 1.0_f64; that is a handy way to see that a number is a float.

Writing to strings and other places

format! builds a String. When you want to append to an existing string (to avoid allocating many temporary strings in a loop) use write! or writeln! with the std::fmt::Write trait in scope. It returns a Result, because writing to some destinations can fail; for a String it never fails, so people call .unwrap() or ignore the result with let _ =.

Rust write! into a String and dbg!

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

dbg! is a debugging tool: it prints something like [main.rs:12:13] a * 21 = 42 to stderr, including the file and line, and then hands the value back, so you can wrap any sub-expression without changing the program. Remove the dbg! calls before you commit; the code stays correct without them. Unlike println!, dbg! moves its argument (taking ownership) and returns it, so with non-Copy values pass a reference: dbg!(&text). Ownership is the subject of the next chapters.

When formatting is expensive or inside tight loops, build output in a String or a buffered writer and print once. Every println! locks standard output and, on a terminal, may flush it. For heavy output wrap stdout in a BufWriter, which I/O traits explains.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line prints Hi, Sam when name is a variable holding "Sam"?

    Plain identifiers can be captured directly inside the braces. Expressions are not allowed in the braces, and Rust does not use + or printf-style %s with println!.
  2. 2. What does {:>8.2} do to the value 3.14159?

    > right-aligns, 8 is the minimum width and .2 is the precision (decimals for floats), so the result is 4 spaces followed by 3.14.
  3. 3. A struct derives Debug only. Which statement compiles?

    {} needs Display, which you must implement yourself. {:?} uses the derived Debug. {:x} and {:e} need LowerHex and LowerExp.
  4. 4. What is the difference between println! and eprintln!?

    println! writes to stdout and eprintln! writes to stderr. Keeping them separate lets users redirect results and diagnostics independently.
  5. 5. How do you print a literal { character?

    Braces are doubled in format strings: {{ prints { and }} prints }.

Summary

  • println!/print! write to stdout, eprintln!/eprint! to stderr, format! returns a String, write!/writeln! write into any writer (a String needs use std::fmt::Write), and dbg! prints to stderr and returns its value.
  • The compiler checks format strings at compile time; the number and types of arguments must match.
  • Fill placeholders by position, by number, by name, or by capturing a variable (); double the braces to print them.
  • {} uses Display (user-facing, implement it yourself), {:?} uses Debug (derive it), and {:#?} pretty-prints.
  • Specs combine fill, alignment (<, ^, >), sign, #, 0, width (also width$), precision (.2) and a type letter (x, X, b, o, e).
  • Floats round halves to even, and money belongs in integers.

Next: Reading Input