Skip to content

Rust Output

You’ve already used println! a bunch of times. This page covers the other printing macros you’ll run into and when to reach for each one.

println! prints text and adds a newline at the end. print! does the same thing but doesn’t add a newline:

fn main() {
print!("Hello, ");
print!("World");
println!("!");
}

Output:

Hello, World!
▶ Try it Yourself

Notice all three calls printed on the same line — only println! breaks to a new one. In practice you’ll use println! almost all the time; print! is mainly useful when you’re building up a line piece by piece.

You’ve seen {} used as a placeholder. You can fill it either by passing a value after the string, or by putting the variable name directly inside the braces:

fn main() {
let name = "Ferris";
let age = 10;
println!("{} is {} years old", name, age); // positional
println!("{name} is {age} years old"); // inline (same result)
}

Both lines print the same thing. The inline style ({name}) is a bit newer and usually easier to read, so prefer it when you can.

format! — build a string instead of printing it

Section titled “format! — build a string instead of printing it”

Sometimes you want the formatted text as a String instead of printing it immediately — say, to store it or pass it to another function. That’s what format! is for. It works exactly like println! but returns a String instead of printing:

fn main() {
let name = "Ferris";
let message = format!("Hello, {name}!");
println!("{message}");
}
▶ Try it Yourself

Plain {} only works for values that know how to display themselves as text — numbers, strings, booleans. For more complex values like tuples or structs, {} won’t compile. Use {:?} (the “debug” format) instead:

fn main() {
let point = (3, 7);
println!("{:?}", point);
}

Output:

(3, 7)
▶ Try it Yourself

For a nicer, multi-line layout on bigger values, use {:#?} (pretty-print):

fn main() {
let point = (3, 7);
println!("{:#?}", point);
}

A few formatting tricks that come up often:

fn main() {
let pi = 3.14159;
println!("{:.2}", pi); // 2 decimal places -> 3.14
println!("{:5}", 42); // pad to width 5 -> " 42"
println!("{:08.2}", pi); // pad with zeros -> 00003.14
}

You don’t need to memorize these — just know they exist for when you need to line up numbers or round decimals.

  • println! prints with a newline; print! doesn’t.
  • {} and {name} are placeholders for values that can Display themselves.
  • format! works like println! but returns a String instead of printing.
  • {:?} (and {:#?}) prints values for debugging, including ones {} can’t handle.