Printing debug output

How to:

To print something simple, use println!. If you need to print a value for debugging, dbg! comes in handy.

fn main() {
    let mut vec = vec![1, 2, 3];
    // Basic printing
    println!("Hello, Rustaceans!");

    // Debug formatting with println! using `{:?}`
    println!("{:?}", vec);

    // Debug with `dbg!`, prints to stderr and returns the value

    // Modifying vec after using `dbg!`

Sample output:

Hello, Rustaceans!
[1, 2, 3]
[src/] &vec = [
[src/] vec = [

Deep Dive

Printing debug output has been a straightforward part of programming since the early days. Its simplicity often makes it a go-to choice for quickly diagnosing problems.

In Rust, println! is great for displaying user-friendly messages. The magic comes with dbg!, introduced in Rust 1.32, which prints both the value and its location in the code. It outputs to standard error (stderr), so it won’t mix with standard output (stdout) and can be separately redirected if needed.

For complex types, you can derive the Debug trait to automatically create a format that println! and dbg! can use. That’s what the #[derive(Debug)] annotation does above your structs and enums.

As for alternatives, proper loggers exist such as log and env_logger, and if you need more granular control, consider a debugger such as gdb or lldb, which work with Rust through integrations like rust-gdb or rust-lldb.

See Also

For more on Rust’s debug printing and formatting options: