Sub topic 3
Hex, binary, octal, and exponent output
Assume you know basic Rust syntax, structs, traits, and cargo run. Rust format strings let you choose how numbers and custom values become text.
Numeric format specifiers
Use x or X for hexadecimal, b for binary, o for octal, and e or E for scientific notation. The # flag adds a radix prefix.
fn main() {
let n = 255;
let pi = 1234.5_f64;
println!("{n:#x} {n:#X} {n:#b} {n:#o}");
println!("{pi:e} {pi:E}");
println!("{n:#010b}");
}The output includes forms such as 0xff, 0b11111111, 0o377, and exponent notation such as 1.234500e3. Width and precision can come from variables:
fn main() {
let value = 3.14159265_f64;
let width = 10;
let precision = 3;
println!("[{value:width$.precision$}]");
println!("[{value:.*}]", 2);
}The first form uses named arguments captured from the surrounding scope. The second takes precision from the next positional argument.
The format macro family
format! returns a String. eprintln! writes to standard error. write! writes formatted text to a writer, including a String.
use std::fmt::Write;
fn main() {
let mut text = String::new();
write!(&mut text, "id={:#x}", 42).unwrap();
println!("{text}");
let message = format!("count={}", 3);
eprintln!("{message}");
}Implementing `Display`
Display defines user-facing output for {}. A type can implement it by writing to the provided formatter.
use std::fmt;
struct Point { x: i32, y: i32 }
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}Use Formatter::pad when the implementation should honor the caller's width, fill, and alignment:
use std::fmt;
struct Tag;
impl fmt::Display for Tag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("tag")
}
}Custom `Debug` and `dbg!`
Implement Debug for safe diagnostic output. You can hide sensitive fields.
use std::fmt;
struct User { name: String, token: String }
impl fmt::Debug for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("User")
.field("name", &self.name)
.field("token", &"<hidden>")
.finish()
}
}dbg!(expression) prints the source location, expression, and value to standard error, then returns the value. It is useful during development.
Compiler checks
Rust checks format strings at compile time. It reports missing arguments, invalid specifiers, and types that lack the required formatting trait. Display and Debug remain separate so user-facing output does not depend on diagnostic output.
Exercise
Which specifier prints 42 as 0b101010, and which trait does {} require?
Show answer
Use {:#b} for the prefixed binary form. The {} placeholder requires Display.