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:
| Parameter | Type | Description |
|---|---|---|
| {} | Display Trait | Formats human-readable string representation. |
| {:?} | Debug Trait | Formats developer diagnostic representation. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Rust Stdin Input: Reading Lines Safely with io::stdin().lock()
Read multi-line pre-supplied stdin efficiently in Rust (rustc 1.85) by locking std::io::stdin() and streaming lines with BufRead.
Rust Default Immutability, the mut Modifier, and Shadowing
Master Rust variable binding model: default immutability, explicit mut modifier, variable shadowing, and compile-time thread safety.
Rust Strings: String vs &str and UTF-8 Slicing
Master String (growable heap string) vs &str (string slice) in Rust.
Rust Type Casting: The as Keyword and Parse Methods
Convert primitive types safely with the as keyword and parse strings with .parse().
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.