liveBook · Manning

Println! macro

As explained in Learn Rust in a Month of Lunches

The println! macro formats its arguments and writes the resulting text followed by a newline to standard output.

`println!` prints text and adds a newline. The `!` matters: it tells Rust this is a macro, not a function. A macro writes code for you, but you do not need to understand how it does that to start printing. section 1.3

fn main() {
    println!("Hello, world number {}!", 8);
}

Run this small example. The `{}` is a placeholder: Rust puts the following argument, `8`, there, producing `Hello, world number 8!`. You can use more placeholders and arguments in the same call. section 1.6

A placeholder is different from a `{}` code block. Inside the quoted text passed to `println!`, it marks where a value should appear. That value can also come from a variable or a function call. section 1.6

Choose a placeholder that suits the value:

  • `{}` uses Display, the usual readable form for types that support it. section 1.8
  • `{:?}` uses Debug, which often shows more information. Try it if the compiler says a type does not implement Display. section 1.8
  • `{:#?}` is Debug with pretty printing, spreading information over more lines. section 1.8

Let the compiler help

Trying `println!("{}", ())` fails because `()` does not support Display. The error suggests `{:?}` or `{:#?}` instead. Similarly, writing `println(...)` without `!` produces a suggestion to invoke the macro as `println!(...)`. section 1.8 section 1.3

Formatting can go further. Use `\n` for a newline within the text and `\t` for a tab; escape a backslash when you want it printed literally. Raw strings can make text with many backslashes easier to read. Other placeholders select binary, hexadecimal or octal numbers, print a reference’s pointer address, choose arguments by position or name, or control padding and alignment. If you do not want the automatic newline, use `print!` instead. section 2.10 section 1.8

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works from basic placeholders through Debug, escapes and formatting options, without explaining macro internals.
Examples
Shows a greeting with an inserted number, a Display compiler error, and examples of number bases and aligned output.
What it assumes
Introduces macro syntax and placeholders from simple examples; defers a fuller understanding of traits.
What you can do after
Apply it in Rust to print formatted values and use compiler feedback to choose a supported placeholder.
How it connects
Connects placeholders to Display, Debug, function arguments, escape sequences and raw strings.

Also explained in

Compare how 2 books explain println! macro →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.