Rustlers Atom 1.10: Formatting

Rust’s formatting is compile-time checked. Placeholders must match the values and the traits they implement.

This are the available macros:

  • println! prints to stdout with a newline.
  • print! prints without a newline.
  • eprintln! prints to stderr.
  • format! builds a String (no I/O).
println!("Hello, {}!", "world");
let s = format!("{} + {} = {}", 2, 3, 2 + 3);

Formatting use this Placeholders and specifiers:

  • {} → uses the value’s Display human-readable implementation.
  • {:?} → uses Debug (requires #[derive(Debug)]).
  • {:#?} → pretty-printed Debug.
  • Named and positional arguments.
  • Common format flags.
println!("{0} {0} {1}", "echo", 42);         
println!("{lang} {ver}", lang="Rust", ver=2021);

println!("{:>6}", 42);       // right align width 6: "    42"
println!("{:<6}", 42);       // left align
println!("{:^6}", 42);       // center
println!("{:06}", 42);       // zero-pad: "000042"
println!("{:.3}", 3.14159);  // precision for floats: "3.142"
println!("{:#x}", 255);      // hex with 0x: "0xff"
println!("{:b}", 13);        // binary: "1101"
println!("{:+}", 7);         // explicit sign: "+7"

Width and precision can come from args:

let w = 8;
let p = 3;
println!("{:0width$.prec$}", 3.14159, width=w, prec=p); // "00003.142"

Writing into buffers/streams

format_args! powers all these macros. You can write to any std::fmt::Write or std::io::Write target.

use std::fmt::Write as _;
let mut s = String::new();
write!(&mut s, "Pi ≈ {:.3}", 3.14159).unwrap();
assert_eq!(s, "Pi ≈ 3.142");

For files/sockets (I/O), use std::io::Write:

use std::io::{Write, stdout};
writeln!(stdout(), "Hi {}", "there")?;

You'll only receive email when they publish something new.

More from GSLF
All posts