Rust:Rust Console Output: println! and Formatting Macros
Rust•Input/Output

Rust Console Output: println! and Formatting Macros

Explore Rust formatting traits: Display ({}) for user output and Debug ({:?}) for programmer inspection.

Syntax

println!("Display: {}", val); println!("Debug: {:?}", struct_val);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
{}Display TraitFormats human-readable string representation.
{:?}Debug TraitFormats developer diagnostic representation.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

#[derive(Debug)]
struct SystemStats {
    service: String,
    latency_ms: f64,
    nodes: u32,
}

fn main() {
    let stats = SystemStats {
        service: String::from("Compilra Edge"),
        latency_ms: 2.345,
        nodes: 12,
    };

    println!("--- Formatted Output ---");
    println!("Service:     {}", stats.service);
    println!("Latency:     {:.2} ms", stats.latency_ms);
    println!("Debug Print: {:?}", stats);
}
Expected Output:
--- Formatted Output ---
Service:     Compilra Edge
Latency:     2.35 ms
Debug Print: SystemStats { service: "Compilra Edge", latency_ms: 2.345, nodes: 12 }

How It Works: Step-by-Step

  • Line 1: #[derive(Debug)] automatically generates Debug printing code.
  • Lines 17-18: {:.2} formats float and {:?} renders full struct structure.

Key Concepts

  • println! is a compile-time checked macro (not a function).
  • Deriving Debug enables instant inspection of any custom struct or enum.

Common Mistake: Attempting to print a struct with {} when Display is not implemented

Custom types do not implement Display by default. Use {:?} with #[derive(Debug)].

❌ Incorrect
println!("{}", myStruct); // Compile Error: doesn't implement std::fmt::Display
✅ Correct
println!("{:?}", myStruct); // Use debug specifier with derive(Debug)

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler