How to print a formatted string in Rust

Created
Modified

Using println!

Prints to the standard output, with a newline. Use the format! syntax to write data to the standard output. See std::fmt for more information.

fn main() {
  let name = "Bob";

  println!("Hello, {}", "World");
  println!("{:?}", ("H", 4));
  println!("{:04}", 12);
  println!("{1} {0}", "a", 13);
  println!("Hello {name}");
  println!("{:0width$}", 12, width = 5);
}
Hello, World
("H", 4)
0012
13 a
Hello Bob
00012

Example

See:

fn main() {
  // Precision
  println!("Float, {:.5}", 0.23);
  println!("Float, {:>7.2}", 0.23);
  println!("Float, {:.*}", 5, 0.23);
  println!("Float, {num:.prec$}", prec = 5, num = 0.23);

  // Escaping
  println!("Hello {{}}");
  println!("Hello {{");
}
Float, 0.23000
Float,    0.23
Float, 0.23000
Float, 0.23000
Hello {}
Hello {

Related macros

There are a number of related macros in the format! family. The ones that are currently implemented are:

format!      // described above
write!       // first argument is a &mut io::Write, the destination
writeln!     // same as write but appends a newline
print!       // the format string is printed to the standard output
println!     // same as print but appends a newline
eprint!      // the format string is printed to the standard error
eprintln!    // same as eprint but appends a newline
format_args! // described below.

Formatting Parameters

Each argument being formatted can be transformed by a number of formatting parameters.

Fill/Alignment
<
the argument is left-aligned in width columns
^
the argument is center-aligned in width columns
>
the argument is right-aligned in width columns
Sign/#/0
+
This is intended for numeric types and indicates that the sign should always be printed. Positive signs are never printed by default, and the negative sign is only printed by default for signed values. This flag indicates that the correct sign (+ or -) should always be printed.
-
Currently not used
#
This flag indicates that the “alternate” form of printing should be used. The alternate forms are:
#?
pretty-print the Debug formatting (adds linebreaks and indentation)
#x
precedes the argument with a 0x
#X
precedes the argument with a 0x
#b
precedes the argument with a 0b
#o
precedes the argument with a 0o
0
This is used to indicate for integer formats that the padding to width should both be done with a 0 character as well as be sign-aware.
Precision
.N
the integer N itself is the precision.
.N$
use format argument N (which must be a usize) as the precision.
.*
.* means that this {...} is associated with two format inputs rather than one: the first input holds the usize precision, and the second holds the value to print.
Formatting traits
?
Debug
x?
Debug with lower-case hexadecimal integers
X?
Debug with upper-case hexadecimal integers
o
Octal
x
LowerHex
X
UpperHex
p
Pointer
b
Binary
e
LowerExp
E
UpperExp

Related Tags